代码:
/** *作者:魏宝航 *2020年11月30日,下午20:50 */ #include<iostream> using namespace std; class Node { public: int data=0; Node* next=NULL; Node() {}; Node(int data) { this->data = data; } }; class LinkedList { public: Node* root = new Node(); //添加元素 void add(int val) { Node* temp = root; while (temp->next != NULL) { temp = temp->next; } Node* s = new Node(val); temp->next = s; } //删除元素 void del(int val) { Node* temp = root; while (temp->next != NULL) { if (temp->next->data == val) { Node* q = temp->next; temp->next = q->next; free(q); break; } temp = temp->next; } } //输出链表 void show() { Node* temp = root->next; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } //修改 void update(int val, int key) { Node* temp = root->next; while (temp != NULL) { if (temp->data == val) { temp->data = key; break; } temp = temp->next; } } }; int main() { LinkedList* list = new LinkedList(); for (int i = 1; i <= 10; i++) { list->add(i); } list->show(); list->del(4); list->show(); list->update(3, 333); list->show(); }