剑指offer--链表中环的入口结点

来源:互联网 发布:java内存泄露场景 编辑:程序博客网 时间:2024/06/15 11:58
[编程题]链表中环的入口结点

一个链表中包含环,请找出该链表的环的入口结点。


参考:点击打开链接


public class 链表中环的入口节点 { public static class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}public static void main(String[] args) {// TODO Auto-generated method stubListNode node1 = new ListNode(1);ListNode node2 = new ListNode(2);ListNode node3 = new ListNode(3);ListNode node4 = new ListNode(4);ListNode node5 = new ListNode(5);node1.next=node2;node2.next=node3;node3.next=node4;node4.next=node5;node5.next=node3;EntryNodeOfLoop(node1);}    public static ListNode EntryNodeOfLoop(ListNode pHead)    {    if (pHead==null||pHead.next==null) {return null;}    ListNode slow = pHead;//速度为1的节点    ListNode fast = pHead;//速度为2的节点    ListNode enterence = null;//入口结点;    ListNode meet = null;    while (fast!=null) {slow = slow.next;fast = fast.next.next;if (fast==slow) {break;}}    if (fast==null) {return null;}    meet = slow;//得到碰撞点;    slow = pHead;//    fast = meet;//重新从起点和meet点走    while (slow!=fast) {slow = slow.next;fast = fast.next;}    enterence = slow;//相遇的点就是入口return enterence;    }}


原创粉丝点击