實現雙向鏈表:建立、插入、刪除 node
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; typedef struct student { int data; struct student *next; struct student *pre; }dnode; //建立鏈表 dnode *create() { //1. 定義變量 dnode *head = NULL; dnode *p = NULL; dnode *s = NULL; int x = 0; int cycle = 1; //2. 新建head head = (dnode*)malloc(sizeof(dnode)); p = head; //3. 添加節點 while(cycle) { printf("input the data:"); scanf("%d", &x); if (x != 0) { s = (dnode*)malloc(sizeof(dnode)); s->data = x; p->next = s; s->pre = p; p = s; } else { cycle = 0; } } //4. 刪除 head p->next = NULL; p = head; head = head->next; free(p); p = NULL; //5. 返回 head return head; } //插入節點 dnode *insert(dnode *head, int num) { //1. 定義變量 dnode *p0 = NULL; dnode *p1 = NULL; p1 = head; //2. 新建節點 p0 = (dnode*)malloc(sizeof(dnode)); p0->data = num; //3. 定位插入位置(升序) while(p0->data > p1->data && p1->next != NULL) { p1 = p1->next; } //4. 插入新節點 if (p0->data > p1->data) //尾 { p1->next = p0; p0->pre = p1; p0->next = NULL; } else { if (head == p1) //頭 { p0->next = p1; p1->pre = p0; head = p0; } else //中間 { p1->pre->next = p0; p0->next = p1; p0->pre = p1->pre; p1->pre = p0; } } //5. 返回 head return head; } //刪除節點 dnode *del(dnode *head, int num) { //1. 定義變量 dnode *p = NULL; p = head; //2. 定位節點 while (num != p->data && p->next != NULL) { p = p->next; } //3. 刪除節點 if (num != p->data) { printf("not found:%d\n", num); } else { if (p == head) //頭 { head = p->next; head->pre = NULL; free(p); } else if (p->next == NULL) //尾 { p->pre->next = NULL; free(p); } else //中間 { p->next->pre = p->pre; p->pre->next = p->next; free (p); } } return head; } //計算鏈表長度 int length(dnode *head) { dnode *p; int n = 0; p = head; while(p != NULL) { p = p->next; n++; } printf("len:%d\n", n); return n; } //顯示 void show(dnode *head) { dnode *p; int n = 0; p = head; while(p != NULL) { printf("data:%d ", p->data); p = p->next; } printf("\n"); } int main() { dnode *head = create(); show(head); length(head); head = insert(head, 2); show(head); head = del(head, 2); show(head); }