160. Intersection of Two Linked Lists
Description:
Write a program to find the node at which the intersection of two singly linked lists begins.
Difficulty:Easy
Note:
1.If the two linked lists have no intersection at all, return null.
2.The linked lists must retain their original structure after the function returns.
3.You may assume there are no cycles anywhere in the entire linked structure.
4.Your code should preferably run in O(n) time and use only O(1) memory.
Example:
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.
方法: 尾端对其
- Time complexity : O ( m + n ) O\left ( m+n\right ) O(m+n)
- Space complexity :
O
(
1
)
O\left ( 1\right )
O(1)
思路:
计算两个链表的长度,按照尾端对其,遍历,看是否有相同元素
另一种方法是虚链表的方法,写起来更简短。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int num_a = 0, num_b = 0;
ListNode *a = headA;
ListNode *b = headB;
while(a) {
num_a++;
a = a->next;
}
while(b) {
num_b++;
b = b->next;
}
if(num_a==0 || num_b==0) return NULL;
if(num_a > num_b) {
int dist = num_a - num_b;
while(dist > 0){
headA = headA->next;
dist--;
}
}
else{
int dist = num_b - num_a;
while(dist > 0){
headB = headB->next;
dist--;
}
}
while(headA&&headB){
if(headA == headB)
return headA;
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};
虚链表
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *cur1 = headA, *cur2 = headB;
while(cur1 != cur2){
cur1 = cur1?cur1->next:headB;
cur2 = cur2?cur2->next:headA;
}
return cur1;
}