1、题目
剑指offer52:两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
2、代码
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;//指针A,先遍历A链表,再遍历B链表,直到走到第一个公共节点与B指针相遇,A指针步数为a+(b-c)
ListNode B = headB;//指针B,先遍历B链表,再遍历A链表,直到走到第一个公共节点与A指针相遇,B指针步数为b+(a-c)
//相遇原理:A指针和B指针按以上走到第一个公共节点时,均走a+b-c步。
while (A != B){
A = (A!=null) ? A.next : headB;
B = (B!=null) ? B.next : headA;
}
return A;
}
}
3、随笔
3.1、测试代码
public static void main(String[] args) {
ListNode headA = new ListNode(4);
ListNode firstNodeA = new ListNode(1);
ListNode secondNodeA = new ListNode(8);
ListNode thirdNodeA = new ListNode(4);
ListNode fourthNodeA = new ListNode(5);
headA.next = firstNodeA;
firstNodeA.next = secondNodeA;
secondNodeA.next = thirdNodeA;
thirdNodeA.next = fourthNodeA;
fourthNodeA.next = null;
ListNode headB = new ListNode(5);
ListNode firstNodeB = new ListNode(0);
ListNode secondNodeB = new ListNode(1);
headB.next = firstNodeB;
firstNodeB.next = secondNodeB;
secondNodeB.next = secondNodeA;
ListNode result = getIntersectionNode(headA,headB);
System.out.println("result.val = " + result.val);
}