相交链表
题目概述
编写一个程序,找到两个链表相交的起点
示例
输入:ListA = 4–>1–>8–>4–>5 ListA = 5–>0–>1–>8–>4–>5
输出:8
题解
如图所示:
将链表拼接起来 形成 ListA----->ListB ListB------>ListA
进行循环 直到ha == hb
return ha;
代码实现
/**
* 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 ha = headA, hb = headB;
while (ha != hb) {
ha = ha != null ? ha.next : headB;
hb = hb != null ? hb.next : headA;
}
return ha;
}
}