C++和链表
想学C++,顺便把以前的坑填一下(
作为练手,我使用了C++实现了链表。
#include <iostream>
#include <cstring>
using namespace std;
// 类
// 是一种高级一点的结构体
class node {
public:
// similar to PHP OOP Access Modifiers
int value;
node* next;
// Why nullptr => https://dzone.com/articles/what-exactly-nullptr-is-in-c
node(int new_value, node* new_next = nullptr) {
value = new_value;
next = new_next;
}
};
// 列出链表中所有node的值,用制表符隔开
int list_all(node *head) {
cout << "All values in this linked list: ";
while(head != nullptr) {
cout << head->value << "\t";
head = head->next;
}
cout << endl;
return 0;
}
// 删除第n个node
int remove_element_by_id(node *head, int number) {
// starts at 0
node* current_ptr = head;
for(int counter = 0; counter < number; counter++) {
current_ptr = current_ptr->next;
if(current_ptr->next == nullptr) {
cout << "Out of range" << endl;
return 1;
}
}
current_ptr->value = current_ptr->next->value;
current_ptr->next = current_ptr->next->next;
return 0;
}
// 获取链表中最后一个node的内存地址
node* traverse_till_the_end(node* head) {
node* current = head;
while(current->next != nullptr) {
current = current->next;
}
return current;
}
// 在链表的最后新增一个node
node* attach(int value, node* head = nullptr) {
node* new_node = new node(value, nullptr);
node* ptr_to_return = nullptr;
node* last_node_in_list = nullptr;
if(head != nullptr) {
last_node_in_list = traverse_till_the_end(head);
last_node_in_list->next = new_node;
ptr_to_return = head;
}
else if(head == nullptr) {
ptr_to_return = new node(value);
}
return ptr_to_return;
}
// 在链表的第n个node的后面插入一个node
node* insert(int value, int number, node* head) {
node* current = head;
for(int i = 0; i < number; i++) {
current = current->next;
if(current->next == nullptr) {
cout << "Index out of range" << endl;
return head;
}
}
node* new_node = new node(value, current->next);
current->next = new_node;
return head;
}
int main() {
cout << "Linked list Demo" << endl;
// 手动创建一个链表
node* node4_ptr = new node(12450);
node* node3_ptr = new node(810 , node4_ptr);
node* node2_ptr = new node(1919 , node3_ptr);
node* node1_ptr = new node(114514, node2_ptr);
// 列出链表中所有node的值
list_all(node1_ptr);
// 往那个链表后面新增东西
attach(777, node1_ptr);
// 往链表的中间插入东西
insert(888, 1, node1_ptr);
list_all(node1_ptr);
// 也可以直接使用 attach() 函数创建新链表
node* new_linkedList = attach(9527);
list_all(new_linkedList);
return 0;
}