LeetCode141:Linked List Cycle

题目:

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;

}

你可能感兴趣的:(LeetCode)