俩个链表的第一个公共节点
1.题意描述
- 输入两个链表,找出它们的第一个公共节点。
2.输入输出描述
- 如下图,公共节点就是8这个节点
3.代码实现
- 第一种方法,用HashSet的不重复性
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
//第一种:用HashSet
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//可以选择set将A全部放进去,然后遍历B,如果有直接返回节点,最后返回null;
Set<ListNode> set = new HashSet<>();
while(headA != null){
set.add(headA);
headA = headA.next;
}
while(headB != null){
if(set.contains(headB)){
return headB;
}
headB = headB.next;
}
return null;
}
}
- 第二种方法;遍历,如果俩个链表长度不一样,让长度一样的先走,等他们俩个长度一致,一起走,然后相同的节点就是结果
在这里插入代码片/**
* 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) {
//2.让链表长度长的先走,直到他们俩个长度一致,然后一起走,直达找到一样的返回,否则就返回null;
int lenA = length(headA); int lenB = length(headB);
while(lenA != lenB){
if(lenA > lenB){
headA = headA.next;
lenA--;
}else{
headB = headB.next;
lenB--;
}
}
//到了这里俩者长度一致,一起走
while(headA != null){
if(headA == headB){
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
//统计链表的长度
private int length(ListNode node) {
int length = 0;
while (node != null) {
node = node.next;
length++;
}
return length;
}
}
- 第三种方法
- 俩个链表同时开始遍历,如果链表A走完,然后从B的头节点开始遍历;
- 同样B走完了,从A的头节点开始遍历;
- 一直到他们俩个遍历的节点重合就是结果;
在这里插入代码片/**
* 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) {
//第三种
//tempA和tempB我们可以认为是A,B两个指针
ListNode tempA = headA;
ListNode tempB = headB;
while (tempA != tempB) {
//如果指针tempA不为空,tempA就往后移一步。
//如果指针tempA为空,就让指针tempA指向headB(注意这里是headB不是tempB)
tempA = tempA == null ? headB : tempA.next;
//指针tempB同上
tempB = tempB == null ? headA : tempB.next;
}
//tempA要么是空,要么是两链表的交点
return tempA;
}
}