题目:
编写一个程序,找到两个单链表相交的起始节点。
思路就是这样:
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// 判空
if (headA == null || headB == null) {
return null;
}
ListNode node1 = headA;
ListNode node2 = headB;
// 向后移动节点,直到headA.val==headB.val
while (node1 != node2) {
node1 = node1 == null ? headB : node1.next;
node2 = node2 == null ? headA : node2.next;
}
return node1;
}
还有一种思路:
代码:
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// 判空
if (headA == null || headB == null) {
return null;
}
int lenA = getLength(headA);
int lenB = getLength(headB);
if (lenA > lenB) {
while (lenA != lenB) {
headA = headA.next;
lenA--;
}
}else {
while (lenA != lenB) {
headB = headB.next;
lenB--;
}
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
// 求链表的长度
public static int getLength(ListNode ld) {
int len = 0;
while (ld != null) {
ld = ld.next;
len++;
}
return len;
}