对好几个月之前看的链表进行了复习。
还是创建头结点,然后依次插入结点。 个人感觉最重要的是对指针/地址的掌握。 只有知道地址的概念,链表的问题也就迎刃而解。
#include <iostream> using namespace std; struct List { int data; List* next; }; void insert(List* node, int dat) { List* newnode = new List(); newnode->next = NULL; newnode->data = dat; List* Last = node; while (Last->next != NULL) { Last = Last->next; } Last->next = newnode; } void print(List* node) { List* newnode = node; while (newnode != NULL) { cout << newnode->data << " "; newnode = newnode->next; } } void add(List* node) { List* head = node; while (head->data != 3) { head = head->next; } List* newnode = new List(); newnode->data = 6; newnode->next = head->next; head->next = newnode; } void del(List* node) { List* head = node; while (head->data != 3) { head = head->next; } head->next = head->next->next; } int main() { List* head = new List(); head->data = 1; head->next = NULL; for (int i = 2; i <= 5; i++) { insert(head, i); //插入2,3,4,5 } print(head); //打印1,2,3,4,5 add(head); //添加6 printf(" "); print(head); //打印1,2,3,6,4,5 del(head); //删除6 printf(" "); print(head); //打印1,2,3,4,5 return 0; }
这次重写的过程不是很顺畅,也思路了一会,希望以后能越来越熟练