雙向迴圈連結串列 和 單向迴圈連結串列 查詢迴圈節點 思路都是一樣。 快慢指標查詢法。 理論可參考
typedef struct Student_Double { char name[10]; int point; struct Student_Double *preStu; struct Student_Double *nextStu; } StudentDouble; StudentDouble * CreateDoubleCircleLink_Table(){ int i = 0; StudentDouble *head = NULL; head=(StudentDouble *)malloc(sizeof(StudentDouble)); head->name[0]='\0'; head->point = 0; head->nextStu = NULL; head->preStu = NULL; //迴圈節點 StudentDouble *cirleStu = NULL; StudentDouble *temp = NULL; StudentDouble *currentNode = head; while (i<=9) { temp = (StudentDouble *)malloc(sizeof(StudentDouble)); strncpy(temp->name,"Node",sizeof(temp->name)); temp->point = i; temp->nextStu = NULL; temp->preStu = currentNode; currentNode->nextStu = temp; currentNode = temp; if (i==3) { cirleStu = currentNode; } i++; } //最後 合併迴圈節點 currentNode->nextStu=cirleStu; return head; } //已知迴圈節點情況查詢迴圈 連結串列,驗證是否可用 void SelectDoubleLinkTable(StudentDouble *student){ StudentDouble *next = student->nextStu; int i = 0; StudentDouble *circleStu = NULL; while (next) { if (circleStu!=NULL&&next->point == circleStu->point) { printf("迴圈節點%d,結束迴圈\n",next->point); break; } if (i==3) { circleStu = next; } printf("index %d; studentName is %s; point is %d\n",i,next->name,next->point); i++; next = next->nextStu; } } //未知情況查詢迴圈節點 StudentDouble * SelectCircleNodeInDoubleLinkTable(StudentDouble *head){ //快慢指標查詢 StudentDouble *fast = head; StudentDouble *slow = head; while (fast) { fast = fast->nextStu->nextStu; slow = slow->nextStu; if (fast==NULL) {//不是迴圈連結串列推出 break; } if (fast==slow) {//快慢指標相遇 break; } } if (fast == NULL) { printf("該連結串列 不是迴圈連結串列\n"); return NULL; } //查詢迴圈節點 fast = head; while (fast!=slow) { fast=fast->nextStu; slow=slow->nextStu; } printf("=====找到迴圈連結串列迴圈節點為%d\n",fast->point); return fast; } int main(void){ char sf[15]; //建立雙向迴圈連結串列 StudentDouble *head = NULL; printf("建立雙向迴圈連結串列Y|N\n"); scanf("%s",sf); if (strcmp(sf,"Y")==0) { head = CreateDoubleCircleLink_Table(); } printf("已知情況查詢迴圈連結串列Y|N \n"); scanf("%s",sf); if (strcmp(sf,"Y")==0) { SelectDoubleLinkTable(head); } printf("未知情況查詢迴圈連結串列Y|N \n"); scanf("%s",sf); if (strcmp(sf,"Y")==0) { SelectCircleNodeInDoubleLinkTable(head); } return 0; }