[Leetcode141]環形連結串列
阿新 • • 發佈:2018-12-15
給定一個連結串列,判斷連結串列中是否有環。
這道題很巧妙,可以用兩個指標去做,一個指標步長為1,另一個步長為2,如果有環的話,就變成了追擊問題,遲早相遇。如果沒環就會最終指向NULL。因為大的步長為2,所以先把連結串列為空或者為一個結點且無環的情況排除。
python:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if head == None: return False if head.next == None: return False slow = head fast = head while fast: slow = slow.next if fast.next : fast = fast.next.next if slow == fast: return True else: return False return False
C++:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL) return false; if(head->next == NULL) return false; ListNode* slow = head; ListNode* fast = head; while(fast){ slow = slow->next; if(fast->next){ fast = fast->next->next; if(fast == slow) return true; } else return false; } return false; } };