Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 Output: Reference of the node with value = 8 Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5].
There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
题意:
描述:给定两个链表,可能相交于某节点。请找出此节点。
Solution1:
1. Find the lengths of two lists
2. Ask longer length list to move diff steps (for loop)
3. Ask two lists to move steps until headA == headB(while loop)
code
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 14 if (headA == null || headB == null) return null; 15 int lenA = getLength(headA); 16 int lenB = getLength(headB); 17 if (lenA > lenB) { 18 for (int i = 0; i < lenA - lenB; ++i) { 19 headA = headA.next; 20 } 21 } else { 22 for (int i = 0; i < lenB - lenA; ++i) { 23 headB = headB.next; 24 } 25 } 26 while (headA != null && headB != null && headA != headB) { 27 headA = headA.next; 28 headB = headB.next; 29 } 30 return (headA != null && headB != null) ? headB : null; 31 } 32 33 public int getLength(ListNode head) { 34 int count = 0; 35 while (head != null) { 36 ++count; 37 head = head.next; 38 } 39 return count; 40 } 41 }