1.查找rear指針為O(1) 那么開始節點就為rear->next->next,也是O(1) //大家可以想象從最后一個結點開始有什么好處
2.head->next ==head 判斷是否空表
//鏈表的定義 typedef struct CLinkList { ElemType data; struct CLinkList; } node ;
1 //插入結點 2 void ds_insert (node **pNode,int i) 3 { 4 node *temp; 5 node *target; 6 node * p; 7 ElemType item; 8 int j=1; 9 printf("輸入要插入結點的值:"); 10 scanf ("%d",&item); 11 12 //插入的節點為頭節點 13 if (i==1) 14 { 15 temp=(*node)malloc(sizeoof (struct CLinkList)); 16 17 if (!temp) 18 exit (0); 19 20 temp->date =item; 21 22 for(target = (*pNode); target->next !=(*pNode); target =target->next);//如果next不是指向頭,不斷循環 23 24 temp->next = (*pNode); 25 target -> next = temp; 26 *pNode = temp; //插入的結點為頭節點,不要漏寫 27 28 } 29 30 else 31 { 32 target =*pNode; 33 34 for (;j<(i-1);++j) //循環到要插入的位置 35 { 36 target =target->next; 37 } 38 temp =(node*)malloc(sizeoof (struct CLinkList)); 39 40 if (!temp) 41 exit(0); 42 43 temp -> data = item; 44 45 p=target -> next; //p先存放要插入位置節點的后一個元素的地址 46 target -> next = temp; //當前結點指向新插入的節點 47 temp -> next = p; //新節點指向本來要插入位置元素的后一個結點 48 } 49 }
1 //刪除節點 2 void ds_detele (node **pNode,int i) 3 { 4 node *target; 5 node *temp; 6 int j=1; 7 if (i==1) 8 { 9 for(target = (*pNode); target->next !=(*pNode); target =target->next);//如果next不是指向頭,不斷循環 10 11 temp = *pNode; 12 13 *pNode =(*pNode)->next; //因為刪除第一個節點,所以把第二個節點賦值給第一個節點,*pNode始終指向第一個節點, 14 target->next =*pNode; //把末節點指向首節點 15 16 free(temp); // 釋放原來的第一個節點 17 } 18 else 19 { 20 target=*pNode; 21 22 for (;j<i-1;++j) //找出要刪除的節點 的前一個節點 23 { 24 target =target->next; 25 } 26 27 28 temp=target->next; 29 target->next=temp->next; // 這兩句等於target=target->next->next 30 31 free(temp); 32 } 33 }
圖片是自己整理思路寫出來的,比較丑,以后寫好點
1 //返回節點的所在的位置 2 int ds_search(node *pNode,int elem) 3 { 4 node *target; 5 int i=1; 6 for (target =pNode;target->datadate !=elem && target->next!=pNode;++i) 7 { 8 target =target->next; 9 } 10 11 if (target->next ==pNode) 12 return 0; 13 14 else 15 return i; 16 }
返回節點比較簡單,大家看看就會
1 //初始化循環鏈表 2 void ds_init (node **pNode) 3 { 4 int item; 5 node *temp; 6 node *target; 7 printf("輸入節點的值,輸入0完成初始化\n"); 8 9 while (1) 10 { 11 scanf ("%d",&item); 12 fflush(stdin); //清除緩沖區,為了不影響下個數的輸入 13 14 if(item==0) 15 return ; 16 17 if(*pNode==NULL) 18 { 19 //循環鏈表只有一個節點 20 *pNode =(node*)malloc(sizeof (struct CLinkList)); 21 22 if(!*pNode) //分配空間失敗,錯誤退出 23 exit (0); 24 25 (*pNode)->data = item ; 26 (*pNode)->next = *pNode; //讓尾節點指向頭節點 27 } 28 29 else 30 { 31 //找到next指向的第一個結點的結點 32 for(target = (*pNode); target->next !=(*pNode); target =target->next);//如果next不是指向頭,不斷循環 33 34 temp=(*node)malloc (size(struct CLinkList)); 35 36 if (!temp) 37 exit(0); 38 39 temp->data =item ; 40 temp->next =*pNode; 41 target->next=temp; 42 43 44 } 45 46 }
感覺不太難,大家琢磨琢磨就會,大家可以寫個解決約瑟夫問題的小程序,挺好玩了。