Subject: Intersecting Linked Lists
- Topic description:
Write a program to find the starting node where two singly linked lists intersect.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
The intersection starts at node c1.
Notice:
- Returns null if the two linked lists do not intersect.
- After returning the result, the two linked lists must still maintain the original structure.
- It can be assumed that there are no loops in the entire linked list structure.
- The program tries to satisfy O(n) time complexity and only uses O(1) memory.
Solution one:
[]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
std::set<ListNode*> node_set; //设置查找集合node_set
while(headA){
node_set.insert(headA); //将链表A中的节点插入node_set
headA = headA->next; //遍历链表A
}
while(headB){
if(node_set.find(headB)!=node_set.end()){
return headB; //当在headB中找到第一个出现在node_set中的节点时
}
headB = headB->next; //遍历链表B
}
return NULL;
}
};
Solution two:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int get_list_length(ListNode *head){
int len = 0;
while(head){ //遍历链表,计算链表长度
len++;
head = head->next;
}
return len;
}
ListNode *forward_long_list(int long_len,int short_len,ListNode *head){
int delta = long_len-short_len;
while(head && delta){ //将指针向前移动至多出节点个数后面的位置
head = head->next;
delta--;
}
return head;
}
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int list_A_len = get_list_length(headA);
int list_B_len = get_list_length(headB);
if(list_A_len>list_B_len){ //如果链表A长,移动headA到对应位置
headA = forward_long_list(list_A_len,list_B_len,headA);
}else{ //如果链表B长,移动headB到对应位置
headB = forward_long_list(list_B_len,list_A_len,headB);
}
while(headA && headB){
if(headA==headB){ //当两个指针指向了同一个节点时,说明找到了
return headA;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};