面试题37:两个链表的第一个公共结点

题目:输入两个链表,找出它们的第一个公共结点。

思路: 如果有的话 肯定是一个T型结构。 可以找到各自长度,然后一个长

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package offer;
public class {
static class ListNode{
int data;
ListNode next;
public ListNode(int data,ListNode next) {
this.data=data;
this.next=next;
}
}
private int size(ListNode node){
int count=0;
if(node==null) return -1;
ListNode d=node;
while(d!=null){
count++;
d=d.next;
}
return count;
}
public ListNode getFirstSameNode(ListNode node1,ListNode node2){
int l1=size(node1);
int l2=size(node2);
ListNode p1 = node1;
ListNode p2 = node2;
if(l1>l2){
for(int i=0;i<l1-l2;i++){
p1=p1.next;
}
while(p1!=null &&p2!=null &&p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p1;
}else{
for(int i=0;i<l2-l1;i++){
p2=p2.next;
}
while(p1!=null &&p2!=null &&p1!=p2){
p1=p1.next;
p2=p2.next;
}
return p2;
}
}
public static void main(String[] args) {
ListNode n6=new ListNode(6,null);
ListNode n5=new ListNode(5,n6);
ListNode n4=new ListNode(4,n5);
ListNode n3=new ListNode(3,n4);
ListNode n2=new ListNode(2,n3);
ListNode n1=new ListNode(1,n2);
ListNode l3=new ListNode(3,n4);
ListNode l2=new ListNode(2,l3);
t37 t=new t37();
System.out.println(t.getFirstSameNode(n1, l2).data);
}
}