C++实现单链表的增删改查

#include #include #include #include using namespace std; int n=0; struct node { int num; struct node*next; }; //创建链表 node *creat() { cout << "输入数据个数:" << endl; cin >> n; node *head; node *p, *r; //p2指向尾部 head = new node; head->next = NULL; cout << "num:" << endl; int num; cin >> num; head->num = num; p=r = head; for (int i = 0; i < n - 1; i++) { p = new node; p->next = NULL; cout << "num:" << endl; cin >> num; p->num = num; r->next = p; r = p; } r->next = NULL; return head; } //删除链表 node *del(node*head, int key) { node *p, *r; //r是要删除的结点 if (head == NULL) { cout << "list null!" << endl; return head; } p = head; while (p->next != NULL) { if (p->next->num == key) { r = p->next; p->next = r->next; delete(r); cout << "删除结点成功!" << endl; return head; } } cout << "不存在该结点!" << endl; return head; } //插入链表 node *insert(node *head, int key) { node *p = new node; node *r = head; p->next = NULL; p->num = key; while (r) { if (r->next->num > key) break; r = r->next; } p->next = r->next; r->next = p; cout << "插入成功!" << endl; return head; } //输出链表 void print(node *head) { node *p = head; while (p) { cout << p->num << ' '; p = p->next; } cout << endl; } int main() { node *head; head=creat(); print(head); cout << "输入要删除的数:" << endl; int key; cin >> key; del(head, key); print(head); cout << "输入要插入的数:" << endl; cin >> key; insert(head, key); cout << "输出最后的链表:" << endl; print(head); return 0; }

【C++实现单链表的增删改查】C++实现单链表的增删改查
文章图片

    推荐阅读