题目描述:
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
题解:
俩个链表相交于一结点,之后的链表肯定是一样的,因为一个结点不可能同时有俩个next。
(1)求出俩个链表的长度len1,len2
(2)俩长度之差记为steps,让长链表先遍历steps个结点
(3)然后俩个链表一起向后走
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int len1 = getLength (pHead1);
int len2 = getLength (pHead2);
int steps = len1 - len2;
ListNode longer = pHead1;
ListNode shorter = pHead2;
if(len1 < len2){
steps = len2 - len1;
longer = pHead2;
shorter = pHead1;
}
for(int i = 0;i < steps;i++){
longer = longer.next;
}
while(longer != shorter){
longer = longer.next;
shorter = shorter.next;
}
return longer;
}
// 计算链表长度
public static int getLength(ListNode head){
int count = 0;
for(ListNode cur = head;cur != null;cur = cur.next){
count++;
}
return count;
}