【Leetcode】Linked List Cycle

来源:互联网 发布:sql数据库获取当前时间 编辑:程序博客网 时间:2024/06/05 04:46

题目要求:

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) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {    }};

解题方法:

fast and slow runner。

在一个环形跑道中,有两个不知疲倦的人在跑步。可以肯定的是,跑的快的人,一定会追上跑的慢的人。这也可以用在这里判断链表是否有环。

两个节点a,b。a每次走两步,b每次只走一步。如果链表有环,那么a一定会赶上b。


code:

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *slow, *fast;        slow = fast = head;        if(head==NULL)  return false;        while(slow && fast && fast->next)        {            slow = slow->next;            fast = fast->next->next; //注意,如果fast在这里可能已经为空,所以在循环中加上判断            if(slow == fast)                return true;        }        return false;    }};


尊重知识的来源: Does everyone solved it with O(n) complexity?

0 0
原创粉丝点击