LeetCode141:Linked List Cycle

mickole發表於2014-02-17

題目:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

解題思路:

判斷連結串列有無環,可用快慢指標進行,快指標每次走兩步,慢指標每次走一步,如果快指標追上了慢指標,則存在環,否則,快指標走到連結串列末尾即為NULL是也沒追上,則無環。

為什麼快慢指標可以判斷有無環?

因為快指標先進入環,在慢指標進入之後,如果把慢指標看作在前面,快指標在後面每次迴圈都向慢指標靠近1,所以一定會相遇,而不會出現快指標直接跳過慢指標的情況。

實現程式碼:

#include <iostream>
using namespace std;

/**
Linked List Cycle
 */
 
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
};
void addNode(ListNode* &head, int val)
{
    ListNode *node = new ListNode(val);
    if(head == NULL)
    {
        head = node;
    }
    else
    {
        node->next = head;
        head = node;
    }
}
void printList(ListNode *head)
{
    while(head)
    {
        cout<<head->val<<" ";
        head = head->next;
    }
}

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL || head->next == NULL)
            return NULL;
        ListNode *quick = head;
        ListNode *slow = head;
        while(quick && quick->next)//利用快慢指標判斷有無環 
        {
            quick = quick->next->next;
            slow = slow->next;
            if(quick == slow)
                return true;
        }
        return NULL;
              
    }
};
int main(void)
{
    ListNode *head = new ListNode(1);
    ListNode *node1 = new ListNode(2);
    ListNode *node2 = new ListNode(3);
    ListNode *node3 = new ListNode(4);
    head->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = node1;
    
    Solution solution;
    bool ret = solution.hasCycle(head);
    if(ret)
        cout<<"has cycle"<<endl;
    
    return 0;
}

相關文章