LintCode(102) 帶環連結串列
阿新 • • 發佈:2019-01-28
題目
給定一個連結串列,判斷它是否有環。
您在真實的面試中是否遇到過這個題? Yes 樣例給出 -21->10->4->5, tail connects to node index 1,返回 true
分析
判斷連結串列有無環的問題,很經典,也是面試中常見的問題。 快慢指標解決。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: True if it has a cycle, or false """ def hasCycle(self, head): # write your code here if head == None or head.next == None: return False slow = head fast = head while fast != None and fast.next != None: slow = slow.next fast = fast.next.next if slow == fast: return True return False
C++程式碼
/** 102 帶環連結串列 給定一個連結串列,判斷它是否有環。 您在真實的面試中是否遇到過這個題? Yes 樣例 給出 -21->10->4->5, tail connects to node index 1,返回 true */ /** * 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: True if it has a cycle, or false */ bool hasCycle(ListNode *head) { // write your code here if(head == NULL || head->next == NULL) { return false; }//if ListNode *slow = head, *fast = head; while(fast != NULL && fast->next != NULL) { fast = fast->next->next; slow = slow->next; if(slow == fast) { return true; }//if }//while return false; } };
GitHub -- C++程式碼