问:找到两个单链表相交的起始节点(假设链表无环):
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Main {
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode pa = headA, pb = headB;
while (pa != pb) {
pa = (pa != null) ? pa.next : headB;
pb = (pb != null) ? pb.next : headA;
}
return pa;
}
public static void main(String[] args) {
// 创建两个链表
ListNode listA = new ListNode(1);
listA.next = new ListNode(2);
listA.next.next = new ListNode(3);
ListNode listB = new ListNode(4);
listB.next = listA.next; // 使得两个链表相交于节点2
ListNode intersectionNode = getIntersectionNode(listA, listB);
System.out.println(intersectionNode.val); // 2
}
}