Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
begin to intersect at node c1.
- 解题思路
首先把两个链表的所有非空结点入栈,然后比较栈顶元素并出栈,直到一个栈为空或者栈顶元素不相等,此时上一次比较的结点即为相交结点。 - 实现代码
/*************************************************************
* @Author : 楚兴
* @Date : 2015/2/8 13:33
* @Status : Accepted
* @Runtime : 76 ms
*************************************************************/
#include <vector>
#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
stack<ListNode*> stack1;
stack<ListNode*> stack2;
ListNode* pa = headA;
ListNode* pb = headB;
while(pa)
{
stack1.push(pa);
pa = pa->next;
}
while(pb)
{
stack2.push(pb);
pb = pb->next;
}
ListNode* temp = NULL;
while (!stack1.empty() && !stack2.empty())
{
if (stack1.top()->val == stack2.top()->val)
{
temp = stack1.top();
stack1.pop();
stack2.pop();
}
else
{
return temp;
}
}
return temp;
}
};
void addListNode(ListNode*& head, int i)
{
ListNode* h = head;
while(h->next != NULL)
{
h = h->next;
}
ListNode* temp = new ListNode(i);
h->next = temp;
}
//void print(ListNode* head)
//{
// ListNode* temp = head;
// while(temp)
// {
// cout<<temp->val<<endl;
// temp = temp->next;
// }
//}
int main()
{
Solution s;
ListNode* headA = new ListNode(0);
addListNode(headA, 1);
addListNode(headA, 2);
addListNode(headA, 1);
addListNode(headA, 2);
addListNode(headA, 3);
ListNode* headB = new ListNode(0);
addListNode(headB, 1);
addListNode(headB, 2);
addListNode(headB, 3);
addListNode(headB, 1);
addListNode(headB, 2);
addListNode(headB, 3);
ListNode* p = s.getIntersectionNode(headA, headB);
cout<<p->val<<endl;
system("pause");
}