Linked List Cycle 找出單鏈表中環路
阿新 • • 發佈:2019-02-05
問題:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解法1:
使用兩個步伐不一樣的指標遍歷連結串列(eg:a每步走一格,b每步走兩格),如果連結串列存在環路,兩個指標總會相遇
/** * 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 == nullptr) return false; ListNode* walker = head; ListNode* runner = head; while(runner->next != nullptr && runner->next->next != nullptr) { walker = walker->next; runner = runner->next->next; if(walker==runner) return true; } return false; } };
解法2:
過河拆橋。每走過一個節點,就將該節點的next指標置為head(相當於將已經走過的節點做標記),如果遇到某個節點的next為head,則說明之前走到過這個節點,有環路。
public class Solution { public boolean hasCycle(ListNode head) { ListNode p = head,pre = head; while(p != null && p.next != null){ if (p.next == head) return true; p = p.next; pre.next = head; pre = p; } return false; } }