import java.util.HashSet;
import java.util.Set;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
ListNode(int x, ListNode next) {
this.val = x;
this.next = next;
}
}
public class Temp {
public static ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
if (headA == null || headB == null)
return null;
ListNode i = headA;
ListNode j = headB;
while (i != j) {
i = (i == null ? headB : i.next);
j = (j == null ? headA : j.next);
}
return i;
}
public static int getListLength(ListNode head) {
int len = 0;
ListNode curr = head;
while (curr != null) {
len++;
curr = curr.next;
}
return len;
}
public static ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
int distance = getListLength(headA) - getListLength(headB);
if (distance < 0) {
ListNode temp = headA;
headA = headB;
headB = temp;
}
distance = Math.abs(distance);
ListNode currA = headA;
ListNode currB = headB;
while (currA != null) {
if (distance-- > 0) {
currA = currA.next;
} else if (currA.val != currB.val) {
currA = currA.next;
currB = currB.next;
} else {
break;
}
}
return currA;
}
public static ListNode getIntersectionNode3(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode intersectionNode = null;
Set<ListNode> nodes = new HashSet<>();
ListNode p = headA;
while (p != null) {
nodes.add(p);
p = p.next;
}
ListNode curr = headB;
while (curr != null) {
if (nodes.contains(curr)) {
intersectionNode = curr;
break;
}
curr = curr.next;
}
return intersectionNode;
}
public static void main(String[] args) {
ListNode _6 = new ListNode(6);
ListNode _2 = new ListNode(2, _6);
ListNode _3 = new ListNode(3, _6);
ListNode _1 = new ListNode(1, _2);
ListNode intersectionNode1 = getIntersectionNode1(_1, _3);
System.out.println(intersectionNode1.val);
ListNode intersectionNode2 = getIntersectionNode2(_1, _3);
System.out.println(intersectionNode2.val);
ListNode intersectionNode3 = getIntersectionNode3(_1, _3);
System.out.println(intersectionNode3.val);
}
}
求两个单链表的交点
最新推荐文章于 2022-09-25 19:55:26 发布