LintCode(103)帶環鏈表 II
來源:程序員人生 發布時間:2016-06-07 08:12:18 閱讀次數:2845次
題目
給定1個鏈表,如果鏈表中存在環,則返回到鏈表中環的起始節點的值,如果沒有環,返回null。
樣例
給出 ⑵1->10->4->5, tail connects to node index 1,返回10
分析
上1題的進階。
首先,利用快慢指針判斷有沒有環,若遇到slow == fast時,跳出循環;
然后,調劑fast=head,slow不變,此時slow與fast同步移動,直至再次相遇,即是鏈表中環的起始節點。
Python代碼
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: The node where the cycle begins.
if there is no cycle, return null
"""
def detectCycle(self, head):
# write your code here
if head == None or head.next == None:
return None
slow = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if fast != None and fast == slow:
fast = head
while fast != slow:
slow = slow.next
fast = fast.next
return fast
return None
GitHub -- Python代碼
C++代碼
/**
103 帶環鏈表 II
給定1個鏈表,如果鏈表中存在環,則返回到鏈表中環的起始節點的值,如果沒有環,返回null。
您在真實的
面試中是不是遇到過這個題? Yes
樣例
給出 ⑵1->10->4->5, tail connects to node index 1,返回10
*/
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins.
* if there is no cycle, return null
*/
ListNode *detectCycle(ListNode *head) {
// write your code here
if(head == NULL || head->next ==NULL)
{
return NULL;
}//if
ListNode *slow = head, *fast = head;
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
break;
}//if
}//while
if(fast && fast == slow)
{
fast = head;
while(fast != slow)
{
fast = fast->next;
slow = slow->next;
}//while
return fast;
}//if
return NULL;
}
};
GitHub -- C++代碼
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈