您的位置:首页 > 其它

leetcode做题总结,题目Intersection of Two Linked Lists 2014/11/27

2014-12-12 04:16 429 查看
题目是两个链表在后面可能合并成一个,如果合并找出合并的点。这个题一开始我的想法是对A链每个节点中间加一个特殊节点,如果历遍B链遇到了这个特殊节点即可找到。但是这个方法有一个问题就是空间复杂度较大。所以我换了个方法将A链首尾相连,这样题目就变成了之前的链表找环形开始的节点的问题了。

public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null)
return null;
if(headA==headB)
return headB;
ListNode q;
ListNode end;
ListNode p = headA;
while(p.next!=null){
p=p.next;
}
end=p;
p=headB;
while(p.next!=null){
p=p.next;
}
if(p!=end)
return null;
end.next=headA;
p=headB;
q=p;
while(true){
p=p.next;
q=q.next.next;
if(p==q)
break;
}
q=headB;
while(p!=q){
p=p.next;
q=q.next;
}
end.next=null;
return q;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: