(LeetCode 141/142)Linked List Cycle
1、Given a linked list, determine if it has a cycle in it.
2、Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
3、Given a linked list, return the length of the cycle, if there is no cycle, return 0;
題目要求:
1、給一個鏈表,判斷它是否存在環;
2、給一個鏈表,如果它存在環,請返回環的起點,否則,返回NULL;
3、給一個鏈表,如果它存在環,請返回環的長度,否則,返回0;
解題思路:
1、判斷是否存在環?
方法1:增加一個set容器,遍歷鏈表,將各個結點依次加入Set集合中,如果該節點已存在集合中,說明存在環;如果遍歷結束后,發現沒有重復的結點,則說明沒有環。
方法2:無需額外空間,設置兩個指針p1,p2,從頭結點開始,一個走一步,p1=p1->next;,一個走兩步,p2=p2->next->next,如果存在環,那么兩個指針肯定會相遇;如果走得快的指針p2到達了終點,說明沒有環。
2、如何求環的起點和環的長度呢?
設鏈表起點距離環的起點距離為a,圈長為n,當p1和p2相遇時,相遇點距離環起點距離為b,此時b已繞環走了k圈,則
p1走的距離為a+b;
p2速度為p1的兩倍,p2走的距離為2*(a+b);
p2走的距離為a+b+k*n=2*(a+b),從而a+b=k*n
即當p1走a步,p2走(k*n-b)步,當k=1時,則為(n-b)步;
因此如何求環的起點?把p1拉回起點重新出發,p2從相遇點繼續走,p1,p2每次均走一步,a步后,p1到達起點,p2也剛好到圈的起點。
如何求環的長度?相遇后,p2再走一圈并統計長度就是圈長。
參考代碼:
1、判斷是否存在環?
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:bool hasCycle(ListNode *head) {set<ListNode*> psets;for(ListNode *p=head;p!=NULL;p=p->next){if(psets.find(p)!=psets.end())return true;psets.insert(p);}return false;} };?
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:bool hasCycle(ListNode *head) { // if(head==NULL || head->next==NULL) // return false;ListNode *p1=head;ListNode *p2=head;while(p2 && p2->next){p1=p1->next;p2=p2->next->next;if(p1==p2)return true;}return false;} };?
2、求環的起點
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode *detectCycle(ListNode *head) {ListNode *p1,*p2;p1=head;p2=head;while(p2 && p2->next){p1=p1->next;p2=p2->next->next;if(p1==p2){// p1 points back to head,p2 still stand where they have met// p1,p2 take the same steps// when they meet again, that's where the cycle startsp1=head;while(p1!=p2){p1=p1->next;p2=p2->next;}return p1;}}return NULL;} };3、求環的長度
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode *detectCycle(ListNode *head) {ListNode *p1,*p2;p1=head;p2=head;while(p2 && p2->next){p1=p1->next;p2=p2->next->next;if(p1==p2){// if p2 cycles around,then the length of cycle can be countedListNode *p=p2->next;int length=1;while(p!=p2){length++;p2=p2->next;}return length;}}return 0;} };總結
以上是生活随笔為你收集整理的(LeetCode 141/142)Linked List Cycle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NuGet学习笔记(2) 使用图形化界面
- 下一篇: Android URLconnectio