LeetCode刷题(C++)——Linked List Cycle(Easy)

来源:互联网 发布:我国的医疗数据网站 编辑:程序博客网 时间:2024/05/29 12:28

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

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

思路:设置两个指针fast和slow,fast一次走两步,slow一次走一步,如果链表有环,两指针一定相遇,并且一定是在环中相遇。否则,链表就没有环

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


原创粉丝点击