带环链表-LintCode

来源:互联网 发布:象牙社区一样的软件 编辑:程序博客网 时间:2024/04/29 14:43

给定一个链表,判断它是否有环。
思想:
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。

#ifndef C102_H#define C102_H#include<iostream>using namespace std;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        ListNode *fast = head, *slow = head;        while (fast&&fast->next)        {            slow = slow->next;            fast = fast->next->next;            if (slow == fast)            {                return true;                break;            }        }        return false;    }};#endif
原创粉丝点击