LeetCode:(142)LinkedList CycleII(java)
阿新 • • 發佈:2018-12-15
package Leetcode_LinkedList; /** * 題目: * 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? */ public class DeleteCycle_93_1014 { public ListNode DeleteCycle(ListNode head) { if (head == null) { return head; } ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) { fast = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } } return null; } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); ListNode node6 = new ListNode(6); ListNode node7 = new ListNode(7); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; node6.next = node7; node7.next = node4; DeleteCycle_93_1014 test = new DeleteCycle_93_1014(); ListNode result = test.DeleteCycle(node1); System.out.println(result.val); } }