[LeetCode]Linked List Cycle II
2014-03-14 17:12
281 查看
原题链接:http://oj.leetcode.com/problems/linked-list-cycle-ii/
题意描述:
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?
题解:
这道题的v1版本是判断一个单链表是否有环,当时我们采用的是快慢指针的方法。传送门:http://www.cnblogs.com/codershell/p/3600100.html
然而本题有所加强,需要找出环的起点。对于一个存在环的单链表,我们有如下示意图:
View Code
题意描述:
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?
题解:
这道题的v1版本是判断一个单链表是否有环,当时我们采用的是快慢指针的方法。传送门:http://www.cnblogs.com/codershell/p/3600100.html
然而本题有所加强,需要找出环的起点。对于一个存在环的单链表,我们有如下示意图:
/** * 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*p = head,*q = head; while(p!=NULL && q!=NULL){ p = p->next; q = q->next; if(q!=NULL) q = q->next; if(p==q) break; } if(q == NULL) return NULL; p = head; while (p != q){ p = p->next; q = q->next; } return q; } };
View Code
相关文章推荐
- leetcode--Linked List Cycle &Linked List Cycle II
- Linked List Cycle II (leetcode)
- leetcode--010 Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode--LinkedListCycleII
- [leetcode]Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode之“链表”:Linked List Cycle && Linked List Cycle II
- [Leetcode-142] Linked List Cycle II(链表有环详细分析)
- [Leetcode][python]Linked List Cycle/Linked List Cycle II
- LeetCode:142. Linked List Cycle II
- [LeetCode] Linked List Cycle II, Solution
- [LeetCode]Linked List Cycle II解法学习
- LeetCode 10 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 I & II
- LeetCode142:Linked List Cycle II