Leetcode-141. 环形链表

题目描述

给定一个链表,判断链表中是否有环。

解答

快慢指针的应用,非常巧妙:快指针每次移两个,慢指针每次移一个,若有环的话两者必能相遇(即两者相等)

代码如下:

/**
 * 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) {
        ListNode *slow = head;
        ListNode *fast = head;
        while(fast!=0&&fast->next!=0&&fast->next->next!=0){
            slow = slow->next;
            fast = fast->next->next;
            if(slow==fast) return true;
        }
        return false;        
    }
};

猜你喜欢

转载自blog.csdn.net/baidu_39622935/article/details/81415715