题目描述
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
https://assets.leetcode.com/uploads/2018/12/13/160_statement.png begin to intersect at node c1. https://assets.leetcode.com/uploads/2020/06/29/160_example_1_1.png
input
intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,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,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
递归版本解题思路
- 使用栈的思想,有交点一定是相同的
- 先将节点都压入栈,然后判断是否是交点
/**
* 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) {
if(headA == nullptr || headB == nullptr){
return nullptr;
}
stack<ListNode*> s1;
stack<ListNode*> s2;
ListNode* node1 = headA;
ListNode* node2 = headB;
while(node1 != nullptr){
s1.push(node1);
node1 = node1 -> next;
}
while(node2 != nullptr){
s2.push(node2);
node2 = node2 -> next;
}
ListNode* res = nullptr;
while(!s1.empty() && !s2.empty()){
node1 = s1.top();
node2 = s2.top();
s1.pop();
s2.pop();
if(node1 == node2){
res = node1;
continue;
}else{
return res;
}
}
return res;
}
};
/**
* 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) {
if(headA == nullptr || headB == nullptr){
return nullptr;
}
stack<ListNode*> s1;
stack<ListNode*> s2;
ListNode* node1 = headA;
ListNode* node2 = headB;
while(node1){
s1.push(node1);
node1 = node1 -> next;
}
while(node2){
s2.push(node2);
node2 = node2 -> next;
}
node1 = s1.top();
node2 = s2.top();
s1.pop();
s2.pop();
if(node1 != node2){
return nullptr;
}
ListNode* res;
while(node1 == node2 && node1 != nullptr){
res = node1;
if(!s1.empty()){
node1 = s1.top();
}else{
return res;
}
if(!s2.empty()){
node2 = s2.top();
}else{
return res;
}
s1.pop();
s2.pop();
}
return res;
}
};