Leetcode 160 Intersection of Two Linked Lists(快慢指针)
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.
题目解析:
Leetcode 里面好多链表的题都可以用快慢指针来解.
这道题的思路就是先遍历两个lists然后得到两个lists的长度, 然后让长的那个lists先走Math.abs(lengthA-lengthB)步, 然后一起走判断下一个节点是不是相等.
注意其中有一步就是两个lists遍历之后要判断最后一个节点是不是相等, 不等就可以直接返回null啦~
1 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 2 if(headA == null && headB == null) 3 return null; 4 ListNode node1 = headA; 5 ListNode node2 = headB; 6 7 int lengthA = 1; 8 int lengthB = 1; 9 while(node1 != null){ 10 lengthA++; 11 node1 = node1.next; 12 } 13 while(node2 != null){ 14 lengthB++; 15 node2 = node2.next; 16 } 17 18 if(node1 != node2) //先判断一下 19 return null; 20 else{ 21 int count = Math.abs(lengthA - lengthB); 22 if(lengthA > lengthB){ //此处处理要注意 23 node1 = headA; 24 node2 = headB; 25 }else{ 26 node2 = headA; 27 node1 = headB; 28 } 29 for(int i = 0; i < count; i++){ 30 node1 = node1.next; 31 } 32 while(node1 != null && node2 != null & node1 != node2){ 33 node1 = node1.next; 34 node2 = node2.next; 35 } 36 37 } 38 return node1; 39 }