求單鏈表的長度(可能有環)
阿新 • • 發佈:2019-02-15
單向連結串列環問題的全面解析(判斷環,環的長度,環的入口)
參照部落格https://my.oschina.net/u/2360415/blog/741253
#include <iostream> using namespace std; struct Node { Node(int x) { value = x; next = 0; } int value; Node *next; }; int getListLength(Node* head) { Node *slow = head; Node *fast = head; while (fast&&fast->next) { slow = slow->next; fast = fast->next->next; if (fast == slow) break; }//如果有環,迴圈結束後,slow=fast是碰撞點-------------------------------- //因為沒有環的情況下,fast有可能停留在NULL位置,也有可能停留在最後一個節點處 //得加上fast->next==NULL if (fast == NULL||fast->next==NULL)//無環 { int len = 0; Node *p = head; while (p) { len++; p=p->next; } //省略 return len; } else { int len1 = 0, len2 = 0;//len1是頭節點到入口點的節點數(不含入口節點),len2是環所有的節點數 Node *p1 = slow; Node *p2 = head; while (p1) { len1++; p1 = p1->next; p2 = p2->next; if (p1 == p2) break; }//迴圈結束後p1=p2是環的入口節點------------------------------- while (slow)//固定碰撞點fast指標 { len2++; slow = slow->next; if (slow == fast) break; } cout << "環長:" << len2 << endl; return len1 + len2; } } int main() { Node *p1 = new Node(1); Node *p2 = new Node(2); Node *p3 = new Node(3); Node *p4 = new Node(4); Node *p5 = new Node(5); Node *p6 = new Node(6); p1->next = p2; p2->next = p3; p3->next = p4; p4->next = p5; p5->next = p6; p6->next = p3;//節點p3是環入口點 cout << getListLength(p1) << endl; return 0; }