标签:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Linked List Two Pointers
这样的实现,时间很快O(n),而且空间O(1)
#include <iostream> using namespace std; /** * 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) { if(head==NULL) return NULL; ListNode * fast=head,*slow=head; while(1){ if(fast->next!=NULL) fast=fast->next; else return NULL; if(fast->next!=NULL) fast=fast->next; else return NULL; slow=slow->next; if(fast==slow) break; } fast=head; while(1){ if(fast==slow) return slow; fast=fast->next; slow=slow->next; } return NULL; } }; int main() { ListNode node1(1),node2(2),node3(3),node4(4),node5(5); node1.next=&node2; node2.next=&node3; node3.next=&node4; node4.next=&node5; node5.next=&node1; Solution sol; ListNode *ret = sol.detectCycle(&node1); if(ret==NULL) cout<<"NULL"<<endl; else cout<<ret->val<<endl; return 0; }
[LeetCode] Linked List Cycle II 链表环起始位置
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4206099.html