Linked List Cycle

来源:互联网 发布:徐州共享网络 编辑:程序博客网 时间:2024/06/16 00:14

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

Follow up:

Can you solve it without using extra space.

https://oj.leetcode.com/problems/linked-list-cycle/

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param head, a ListNode    # @return a boolean    def hasCycle(self, head):        if head is None:            return False        p = head        q = head        while p is not None and q is not None :            p = p.next            if q.next is None:                return False            q = q.next.next            if p == q :                return True        return False


0 0
原创粉丝点击