您的位置:首页 > 其它

leetcode Linked List Cycle II

2015-09-01 10:34 393 查看
题目链接

思想:

首先判断是不是有圈

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

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;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: