[LeetCode] Linked List Cycle

来源:互联网 发布:自动化办公软件下载 编辑:程序博客网 时间:2024/05/19 20:48

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

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

解题思路

使用快慢两个指针,如果快的指针赶上了慢的,则说明存在回路。

实现代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *///Runtime:18 msclass Solution {public:    bool hasCycle(ListNode *head) {        if (head == NULL)        {            return false;        }        ListNode *slow = head;        ListNode *fast = head;        while (fast->next && fast->next->next)        {            slow = slow->next;            fast = fast->next->next;            if (fast == slow)            {                return true;            }        }        return false;    }};
0 0
原创粉丝点击