题目

输入两个链表,找出它们的第一个公共节点。

两个链表的第一个公共节点_数据结构

分析

第一种方式:先统计两链表长度,然后减去差值,让长的链表先走差值个位置为了让两个链表同一起跑线同时遍历,遍历同时比较值大小这样就找到了相遇节点。代码比较冗长,时间复杂度O(n)。

两个链表的第一个公共节点_两个指针_02


第二种方式:两个链表同时遍历,当其中一个链表遍历到空时,就直接指向另一个链表的头节点接着遍历,直到两个指针相遇为止。

设交集链表长c,链表1除交集的长度为a,链表2除交集的长度为b,有

a + c + b = b + c + a

若无交集,则a + b = b + a, 最后两个指针同时指向null,这样俩指针一样是相等跳出while了

代码

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
int lengthA=0,lengthB=0;
ListNode temp=headA;
while(temp!=null){
lengthA++;
temp=temp.next;
}
temp=headB;
while(temp!=null){
lengthB++;
temp=temp.next;
}
int sub;
if(lengthA>lengthB){
sub=lengthA-lengthB;
while(sub-->0){
headA=headA.next;
}
}else{
sub=lengthB-lengthA;
while(sub-->0){
headB=headB.next;
}
}
while(headA!=null){
if(headA==headB) return headA;
headA=headA.next;
headB=headB.next;
}
return null;


}
}

两个链表的第一个公共节点_链表_03

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
ListNode A = headA;
ListNode B = headB;
while(A != B){
A = A == null ? headB : A.next;
B = B == null ? headA : B.next;
}
return A;
}
}

两个链表的第一个公共节点_时间复杂度_04