1. 题目
2. 题解
(1)朴素解法
- 直接遍历两个链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
for(ListNode a = headA; a != null; a = a.next){
for(ListNode b = headB; b != null; b = b.next){
if(a == b)
return a;
}
}
return null;
}
}
(2)栈
- 从后往前,将两条链表分别压入两个栈中
- 然后循环比较两个栈的栈顶元素,同时记录上一位栈顶元素。
- 当遇到第一个不同的节点时,结束循环,上一位栈顶元素即是答案。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Deque<ListNode> stack1 = new LinkedList<>();
Deque<ListNode> stack2 = new LinkedList<>();
while (headA != null) {
stack1.push(headA);
headA = headA.next;
}
while (headB != null) {
stack2.push(headB);
headB = headB.next;
}
ListNode ans = null;
while (!stack1.isEmpty() && !stack2.isEmpty() && stack1.peek() == stack2.peek()) {
ans = stack1.pop();
stack2.pop();
}
return ans;
}
}
(3)Set解法
- 使用 Set 数据结构,先对某一条链表进行遍历,同时记录下来所有的节点。
- 然后在对第二链条进行遍历时,检查当前节点是否在 Set 中出现过,第一个在 Set 出现过的节点即是交点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while (headA != null) {
set.add(headA);
headA = headA.next;
}
while (headB != null && !set.contains(headB))
headB = headB.next;
return headB;
}
}
(4)差值法
- 由于两条链表在相交节点后面的部分完全相同,因此我们可以先对两条链表进行遍历,分别得到两条链表的长度,并计算差值 d。
- 让长度较长的链表先走 d 步,然后两条链表同时走,第一个相同的节点即是节点。
- 时间复杂度为 a + b (a,b分别为两个链表长度)
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lena = 0, lenb = 0;
ListNode a = headA, b = headB;
while(a != null){
lena++;
a = a.next;
}
while(b != null){
lenb++;
b = b.next;
}
int d = lena - lenb;
if(d > 0){
while(d-- > 0)
headA = headA.next;
}else if(d < 0){
d = -d;
while(d-- > 0)
headB = headB.next;
}
while(headA != headB){
headA = headA.next;
headB = headB.next;
}
return headA;
}
}
(5)带点数学
考虑构建两个节点指针 A , B 分别指向两链表头节点 headA , headB ,做如下操作:
-
指针 A 先遍历完链表 headA ,再开始遍历链表 headB ,当走到 node 时,共走步数为:
a + (b - c) -
指针 B 先遍历完链表 headB ,再开始遍历链表 headA ,当走到 node 时,共走步数为:
b + (a - c)
如下式所示,此时指针 A , B 重合,并有两种情况:
-
a + (b - c) = b + (a - c)
-
若两链表 有 公共尾部 (即 c > 0c>0 ) :指针 A , B 同时指向「第一个公共节点」node 。
-
若两链表 无 公共尾部 (即 c = 0c=0 ) :指针 A , B 同时指向 nullnull 。
-
因此返回 A 即可。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}