- 输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
- 计算出两个差表的长度,同时开始查询
- C++ 代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1 = countLength(pHead1);
int len2 = countLength(pHead2);
if(len1 > len2) {
int diff = len1 - len2;
while((diff--)>0){
pHead1 = pHead1.next;
}
} else if(len2 > len1){
int diff = len2 - len2;
while((diff--)>0){
pHead2 = pHead2.next;
}
}
return commomHead(pHead1, pHead2);
}
private int countLength(ListNode head) {
int len = 0;
ListNode p = head;
while(p != null) {
len++;
p = p.next;
}
return len;
}
private ListNode commomHead(ListNode pHead1, ListNode pHead2){
while(pHead1!=null && pHead2!=null) {
if(pHead1 == pHead2) return pHead1;
else {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
}
return null;
}
}
网友评论