判斷連結串列是否有環,並返回連結串列的第一個節點
阿新 • • 發佈:2018-12-26
class Solution { private static ListNode function(ListNode head) { if (head == null || head.next == null || head.next.next == null) { return null; } ListNode slow = head.next; ListNode fast = head.next.next; while (slow != fast) { slow = slow.next; if (fast.next == null || fast.next.next == null) { return null; } fast = fast.next.next; } fast = head; while (slow != fast) { slow = slow.next; fast = fast.next; } return fast; } private static void print(ListNode head) { while (head != null) { System.out.println(head.val); head = head.next; } } private static void printEle(ListNode node) { if (node == null) { System.out.println("null"); } else { System.out.println(node.val); } } public static void main(String[] args) { ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; // n5.next = n2; ListNode head = function(n1); printEle(head); // print(head); } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }