Linked List Cycle II
2015-01-09 09:57
204 查看
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?
这题和上一题不一样,我们要返回圈的初始节点。
首先我们先判断是不是一个环,那么我们可以得到这个环中的一个节点。
那么 我们就能根据这个节点 得到这个环中的节点数。那么就可以像求一个链表中第k个节点一样,用两个指针得到。
null.
Follow up:
Can you solve it without using extra space?
这题和上一题不一样,我们要返回圈的初始节点。
首先我们先判断是不是一个环,那么我们可以得到这个环中的一个节点。
那么 我们就能根据这个节点 得到这个环中的节点数。那么就可以像求一个链表中第k个节点一样,用两个指针得到。
/** * 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 *pFirst = head; ListNode *pSecond = head; ListNode *pCircle = NULL; while(pFirst!=NULL&&pSecond!=NULL) { pFirst = pFirst->next; pSecond = pSecond->next; if(pSecond!=NULL) pSecond = pSecond->next; else return NULL; if(pFirst==pSecond) { pCircle = pFirst; break; } } if(!pCircle) return NULL; ListNode *pCur = pCircle->next; int len = 1; while(pCur!=pCircle) { pCur = pCur->next; len++; } pFirst = head; pSecond = head; for(int i =0;i<len;i++) pSecond = pSecond->next; while(pFirst!=pSecond) { pFirst = pFirst->next; pSecond = pSecond->next; } return pSecond; } };
相关文章推荐
- [LeetCode] Linked List Cycle II
- [leedcode 142] Linked List Cycle II
- linked-list-cycle-ii
- 141、142 Linked List Cycle & II
- [LeetCode] Linked List Cycle II 单链表中的环之二
- Linked List Cycle II
- Linked List Cycle II
- LeetCode | Linked List Cycle II
- 【LeetCode】Linked List Cycle II
- 142. Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 142. Linked List Cycle II
- [leetcode 142]Linked List Cycle II
- 【LeetCode】Linked List Cycle II
- [leetcode][list][two pointers] Linked List Cycle II
- leetcode day5 -- Reorder List && Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 142. Linked List Cycle II