LeetCode 142. Linked List Cycle II

来源:互联网 发布:sql优化书籍推荐 编辑:程序博客网 时间:2024/06/08 15:58

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

对于寻找重合点来说,必须要是用快慢指针,因此slow = head

fast = head.next

java

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def detectCycle(self, head):        """        :type head: ListNode        :rtype: ListNode        """        if head is None or head.next is None:            return None        node = self.getCycle(head)        if node is None:            return None        while head is not node.next:            node = node.next            head = head.next        return head            def getCycle(self, head):        if head is None or head.next is None:            return None        slow, fast = head, head.next        while fast.next is not None and fast.next.next is not None:            if fast == slow:                return slow            else:                fast = fast.next.next                slow = slow.next        return None        

python

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode detectCycle(ListNode head) {        if (head == null || head.next == null) {            return null;        }        ListNode node = getCycle(head);        if (node == null) {            return null;        }        while (head != node.next) {            head = head.next;            node = node.next;        }        return head;    }        private ListNode getCycle(ListNode head) {        if (head == null || head.next == null) {            return null;        }        ListNode slow = head;        ListNode fast = head.next;        while (fast.next != null && fast.next.next != null) {            if (fast == slow) {                return slow;            }            fast = fast.next.next;            slow = slow.next;        }        return null;    }}


原创粉丝点击