[leetcode][list][two pointers] Linked List Cycle II
2015-05-22 14:33
337 查看
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
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?
/** * 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(NULL == head || NULL == head->next) return NULL; ListNode *slow = head; ListNode *fast = head->next; while(fast && fast->next && slow != fast){ slow = slow->next; fast = fast->next->next; } if(slow != fast) return NULL;//无环 //计算环中元素个数n int cnt = 1; slow = slow->next; while(slow != fast){ ++cnt; slow = slow->next; } //前后指针,一个指针先走n部,然后两个指针同步向前,相遇点就是入口 ListNode *front = head; ListNode *behind = head; for(int i = 0; i < cnt; ++i) front = front->next; while(front != behind){ front = front->next; behind = behind->next; } return front; } };
相关文章推荐
- 142. Linked List Cycle II (List; Two-Pointers)
- [leetcode][list][two pointers] Reverse Linked List II
- [leetcode][list][two pointers] Linked List Cycle
- LeetCode:142. Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode linked-list-cycle(i 、ii)(java实现)
- leetcode之Linked List Cycle II
- [leetcode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode-Linked List Cycle II
- LeetCode:Linked List Cycle II
- leetcode 142: Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- LeetCode: Linked List Cycle II
- [Leetcode]Linked List Cycle II
- LeetCode "Linked List Cycle II"
- leetcode-Linked List Cycle II
- LeetCode Linked List Cycle II
- LeetCode:Linked List Cycle && Linked List Cycle II
- LeetCode Linked List Cycle II(Floyd 判圈算法)