您的位置:首页 > 其它

Intersection of Two Linked Lists

2015-07-03 15:56 190 查看
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:
A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return
null
.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

Credits:

Special thanks to @stellari for adding this problem and creating all test cases.

Show Tags

Have you met this question in a real interview?
Yes

No

思路:假设listA的长度为m,listB的长度为n,只要A中有一个元素在B中出现,那么A,B从那个元素起,后面的都是重合的。

具体可见剑指offer的两个链表的第一公共节点那一题。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
//剑指offer的第37题P194
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
//求出ListA的长度和ListB的长度
int lenA = 0;
ListNode pa = headA;
int lenB = 0;
ListNode pb = headB;
while(pa!=null){
lenA++;
pa = pa.next;
}
while(pb!=null){
lenB++;
pb = pb.next;
}

//调整pa和pb的位置,使得大家的剩余长度一样。
pa = headA;
pb = headB;
if(lenB>lenA){
int c = lenB-lenA;
while(c>0){
pb=pb.next;
c--;
}
}
if(lenA>lenB){
int c = lenA-lenB;
while(c>0){
pa=pa.next;
c--;
}
}

//调整完毕,开始一个一个的比较,找公共点
while(pa!=null){
if(pa.val == pb.val){
return pa;
}else{
pa = pa.next;
pb = pb.next;
}
}
return null;

}
}
还有利用堆栈的方法来做,但是空间换时间,具体也见书上的分析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: