两个链表的第一个公共节点
题目:输入两个链表,找出它们的第一个公共节点。
起点相同
首先计算两个链表的长度,如果不一样长,就让长的链表先走,知道链表长度相同,接下来两个链表同时移动,对比节点是否一样,相同则说明该点就是两链表的交点。
代码
/**
* 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) {
int lenA = length(headA),lenB = length(headB);
while (lenA != lenB){
if (lenA > lenB){
headA = headA.next;
lenA--;
}
else{
headB = headB.next;
lenB--;
}
}
while (headA != headB){
headA = headA.next;
headB = headB.next;
}
return headA;
}
private int length(ListNode node){
int i = 0;
while (node != null){
i++;
node = node.next;
}
return i;
}
}
双指针
代码
/**
* 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) {
ListNode tempA = headA;
ListNode tempB = headB;
while (tempA != tempB){
tempA = tempA == null ? headB:tempA.next;
tempB = tempB == null ? headA:tempB.next;
}
return tempA;
}
}