141. Linked List Cycle

来源:互联网 发布:网络媒介的演变 编辑:程序博客网 时间:2024/06/07 06:34

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

这个题目记住就可以,没做过的还真不一定能想到

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

python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        if head is None or head.next is None:            return False        slow, fast = head, head.next        while True:            if fast.next is None or fast.next.next is None:                return False            if slow is fast:                return True            slow = slow.next            fast = fast.next.next              


原创粉丝点击