forked from marsprince/SwordForOffer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindFirstCommonCode.java
More file actions
54 lines (51 loc) · 1.09 KB
/
FindFirstCommonCode.java
File metadata and controls
54 lines (51 loc) · 1.09 KB
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
package Problem37;
public class FindFirstCommonCode {
/*
* 求两个单向链表的第一个公共节点
*/
public ListNode findFirstCommonNode(ListNode root1,ListNode root2)
{
int length1=getLength(root1);
int length2=getLength(root2);
ListNode pointLongListNode=null;
ListNode pointShortListNode=null;
int dif=0;
if(length1>length2)
{
pointLongListNode=root1;
pointShortListNode=root2;
dif=length1-length2;
}
else {
pointLongListNode=root2;
pointShortListNode=root1;
dif=length2-length1;
}
for(int i=0;i<dif;i++)
pointLongListNode=pointLongListNode.nextNode;
while(pointLongListNode!=null && pointShortListNode!=null && pointLongListNode!=pointShortListNode)
{
pointLongListNode=pointLongListNode.nextNode;
pointShortListNode=pointShortListNode.nextNode;
}
return pointLongListNode;
}
private int getLength(ListNode root)
{
int result=0;
if(root==null)
return result;
ListNode point=root;
while(point!=null)
{
point=point.nextNode;
result++;
}
return result;
}
}
class ListNode
{
int data;
ListNode nextNode;
}