Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
Tips:找到两个链表的第一个公共结点。
解题思路:先计算两个链表的长度,将较长的链表即为node1.较短的记为node2.
计算两个链表长度差为diff。让node1先向前移动diff个结点,之后再让两个链表同时向后移动,直到到达两个链表的公共结点。
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int len1=getLength(headA); int len2=getLength(headB); ListNode node1=headA; ListNode node2=headB; //将长的赋值给1 if(len1<len2){ int temp=len1; len1=len2; len2=temp; node1=headB; node2=headA; } int diff=len1-len2; for(int i=0;i<diff;i++){ node1=node1.next; } while(node1!=null && node2!=null && node1!=node2){ node1=node1.next; node2=node2.next; } ListNode ans=new ListNode(0); if(node1==node2){ ans=node1; }else{ ans=null; } return ans; } private int getLength(ListNode head) { //计算链表长度 ListNode node=head; int count=0; while(node!=null){ node=node.next; count++; } return count; }