LeetCode 题解(47): Linked List Cycle

来源:互联网 发布:got it 和get it的区别 编辑:程序博客网 时间:2024/06/06 02:43

题目:

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

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


题解:

<pre name="code" class="cpp">/** * 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 || !head->next)            return false;        ListNode* one = head;        ListNode* two = head;        do {            one = one->next;            if(!two->next)                return false;            two = two->next->next;            if(!two)                return false;                        } while(one != two);        return true;    }};



同样的思想,更简单的写法

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode* p, *q;        p = q = head;        while(q && q->next) {            p = p->next;            q = q->next->next;                        if(p == q)                return true;        }        return false;    }};

Java版

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public boolean hasCycle(ListNode head) {        ListNode p, q;        p = q = head;        while(q != null && q.next != null) {            p = p.next;            q = q.next.next;            if(p == q)                return true;        }        return false;    }}

Python版

class Solution:    # @param head, a ListNode    # @return a boolean    def hasCycle(self, head):        p = head        q = head        while q != None and q.next != None:            p = p.next            q = q.next.next            if p == q:                return True        return False


0 0