寫了一個刪除雙鏈表節點的程序,在這里記錄一下,直接上代碼,代碼中的主要步驟都有注釋。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include <assert.h> 5 typedef struct NODE{ 6 struct NODE *prior; 7 struct NODE *next; 8 int value; 9 }Node; 10 void print(Node* rootp) 11 { 12 if(rootp==NULL) 13 exit(1); 14 Node*tmp=rootp->next; 15 while(tmp) 16 { 17 printf("value=%d\n",tmp->value); 18 tmp=tmp->next; 19 } 20 } 21 int dll_insert(Node *rootp,int value); 22 int dll_remove(Node *rootp,Node* node); 23 int main () 24 { 25 Node *p1=(Node*)malloc(sizeof(struct NODE)); 26 if(p1==NULL) 27 return -1; 28 p1->prior=NULL; 29 p1->next=NULL; 30 //p1->value=10; 31 int value; 32 printf("輸入要插入的值\n"); 33 while(scanf("%d",&value)==1) 34 dll_insert(p1,value); 35 36 print(p1); 37 getchar(); 38 printf("輸入要刪除的值\n"); 39 Node*del=(Node*)malloc(sizeof(Node)); 40 41 scanf("%d",&del->value); 42 if(dll_remove(p1,del)) 43 { 44 printf("沒有要刪除的節點\n"); 45 exit(2); 46 } 47 print(p1); 48 return 0; 49 } 50 int dll_remove(Node *rootp,Node* node) 51 { 52 assert(node!=NULL);//斷言node節點不為空 53 Node *this=rootp->next; 54 55 while(this!=NULL) 56 { 57 if(this->value==node->value) 58 break; 59 this=this->next; 60 } 61 if(this->value==node->value) 62 { 63 if(this->prior==NULL)//this的前驅是rootp指針 64 rootp->next=this->next;//先把this前驅的后繼指向this的后繼 65 else 66 this->prior->next=this->next; 67 if(this->next==NULL) //this是最后一個節點 68 rootp->prior=this->prior; 69 else//把this后繼的前驅指向this的前驅 70 this->next->prior=this->prior; 71 free(this); 72 return 0; 73 } 74 return -1; 75 } 76 /*在任何一種情況下,新節點都應該插入this的next,新節點的next 77 指向next節點*/ 78 /*根節點的next字段指向鏈表第一個節點,prior字段指向最后一個節點 79 如果鏈表為空,這兩個字段都為NULL*/ 80 /*鏈表第一個節點的prior字段和最后一個節點的next字段為NULL*/ 81 int dll_insert(Node *rootp,int value) 82 { 83 Node* this; 84 Node* next; 85 Node* new ; 86 for(this=rootp;(next=this->next)!=NULL;this=next) 87 { 88 if(next->value==value)//雙向鏈表中存在value值,退出 89 return 0; 90 if(next->value>value)//當前值大於要插入的值 91 break; 92 } 93 new=(Node*) malloc(sizeof(struct NODE)); 94 if(new==NULL) 95 return -1; 96 new->value=value; 97 98 /*在任何一種情況下,新節點都應該插入this的next,新節點的next 99 指向next節點*/ 100 new->next=next; 101 this->next=new; 102 if(this!=rootp) 103 new->prior=this; 104 else 105 new->prior=NULL;//this就是根指針,也就是new為第一個節點,所以prior為NULL 106 if(next!=NULL) 107 next->prior=new; 108 else 109 rootp->prior=new; 110 //next值為NULL說明new為最后一個節點,所以根指針的prior字段指向new 111 return 1;//插入成功 112 }