141. Linked List Cycle

problem

141. Linked List Cycle

 code

这道题是快慢指针的经典应用。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。实在是太巧妙了,要是我肯定想不出来。代码如下:

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

 

 

 

1.Leetcode_Linked List Cycle;

2. 

https://www.cnblogs.com/grandyang/p/4137187.html

posted on 2018-12-04 10:26  鹅要长大  阅读(102)  评论(0编辑  收藏  举报

导航