[LeetCode] Intersection of Two Linked Lists
来源:互联网 发布:tcp ip网络编程 代码 编辑:程序博客网 时间:2024/06/04 23:26
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");}
0 0
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- leetcode:Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- leetcode Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- VolleyLog-学习Google封装的Log
- UVA 11437 || Triangle Fun
- Java的抽象类和接口
- 用Powershell对文件批量重命名
- web页面树形下拉选择框
- [LeetCode] Intersection of Two Linked Lists
- 线段树模板
- split的简单使用
- 九度OJ题目1202:排序
- 《数据可视化实战:使用D3设计交互式图表 》笔记
- try catch 异常处理
- 层次遍历
- NodeJS笔记
- 基于cxfwebservice01