题目:输入两个链表,找出它们的第一个公共结点。
这个题应该算是倒数第k个节点的一个简化版
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null){
return null;
}
int length1 = getListLength(pHead1);
int length2 = getListLength(pHead2);
boolean one = length1 > length2;
int distance = one ? length1 - length2 : length2 - length2;
if(one){
pHead1 = walkDistance(pHead1, distance);
}else{
pHead2 = walkDistance(pHead2, distance);
}
while(pHead1 != null){
if(pHead1 == pHead2){
return pHead1;
}
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
int getListLength(ListNode pHead){
int length = 0;
while(pHead != null){
pHead = pHead.next;
length++;
}
return length;
}
ListNode walkDistance(ListNode pHead, int distance){
while(distance != 0){
pHead = pHead.next;
distance--;
}
return pHead;
}
}
我们要知道这样一件事,如果因为一个节点只有一个next指针,那么如果两个链表有公共节点,他们公用一个尾巴
计算出两个节点的长度,并求差值d,让较长的链表先走d个节点,然后两个链表同时出发,他们就会同时到达公共节点。
网友评论