单链表操作

来源:互联网 发布:网络机顶盒品牌排行 编辑:程序博客网 时间:2024/04/26 00:18
#include <iostream>using namespace std;struct Node{int data;Node* next;};Node* create(){Node *head = new Node();head->data = 0;head->next = NULL;for (int i = 10; i > 0; --i){Node *temp = new Node();temp->data = i;temp->next = NULL;temp->next = head->next;head->next = temp;}return head;}void print(Node *head){while (head != NULL){cout << head->data << " ";head = head->next;}cout << endl;}Node* findLastNode(Node* head, int data){while (head != NULL && head->data != data){head = head->next;}return head;}void deleteNode(Node* head, Node* del){if (del->next != NULL){del->data = del->next->data;del->next = del->next->next;}else//删除的是最后节点{Node* pre = findLastNode(head, 9);pre->next = pre->next->next;}}bool insertNode(Node* head, int new_value){Node *previous;Node *newNode;previous = nullptr;//顺序访问、当其值大于或等于时创建新节点while (head != nullptr && head->data < new_value){previous = head;head = head->next;}newNode = (Node*)malloc(sizeof(Node));if (NULL == newNode){return false;}newNode->data = new_value;newNode->next = head;//head 已经变成了head->next\当传入的值为12是head==nullptrif (previous == nullptr)//previous保存的head{head = newNode;//插入在表头}else{previous->next = newNode;//插入在表尾}return true;}int main(int argc, char *argv[]){Node *head = create();print(head);Node *delNode = findLastNode(head, 8);deleteNode(head, delNode);print(head);Node *del = findLastNode(head, 10);deleteNode(head, del);print(head);//列表的插入insertNode(head, 12);print(head);cin.get();return 0;}


0 0