leetcode Linked List Cycle II

来源:互联网 发布:手机建筑图纸软件 编辑:程序博客网 时间:2024/06/08 10:03

题目链接

思想:
首先判断是不是有圈

如果有圈的话可以找两个列表的第一个公共节点。这两个链表分别是
head->……->tail

tail->….tail

/** * 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)        {            return null;        }        ListNode pre=head;        ListNode tail=head;        while(true)        {            if(pre!=null&&pre.next!=null)            {                pre=pre.next.next;                tail=tail.next;            }            else            {                break;            }            if(pre==tail)            {                return getIntersectionNode(pre,head);            }        }           return null;    }    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        ListNode temp;        //求长度        int linkALength=0;        temp=headA;        while(temp!=headA)        {            temp=temp.next;            linkALength++;        }        int linkBLength=0;        temp=headB;        while(temp!=headB)        {            temp=temp.next;            linkBLength++;        }        //对齐        ListNode linkA=headA;        ListNode linkB=headB;        if(linkALength>linkBLength)        {            for(int i=0;i<linkALength-linkBLength;i++)            {                linkA=linkA.next;            }        }        else        {            for(int i=0;i<linkBLength-linkALength;i++)            {                linkB=linkB.next;            }        }        while(linkA!=null&&linkB!=null)        {            if(linkA==linkB)            {                return linkA;            }            linkA=linkA.next;            linkB=linkB.next;        }        return null;    }}
0 0
原创粉丝点击