leetcode-Intersection of Two Linked Lists-160
来源:互联网 发布:pkpm软件多少钱 编辑:程序博客网 时间:2024/06/10 08:33
网上看到两种方法:
1.找出两个链表的长度,然后长的那个先走lenmax-lenmin步,之后一起遍历,找到相同的就返回。这个得遍历两次链表。
/** * 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) { int len1=0,len2=0; ListNode* p=headA; ListNode* q=headB; while(p){ len1++; p=p->next; } while(q){ len2++; q=q->next; } p=headA; q=headB; if(len2>len1){ int len=len2-len1; while(len--){ q=q->next; } while(p){ if(p==q) return p; p=p->next; q=q->next; } } else{ int len=len1-len2; while(len--){ p=p->next; } while(p){ if(p==q) return p; p=p->next; q=q->next; } } return NULL; }};
/** * 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==NULL||headB==NULL) return NULL; stack<ListNode*> s1; stack<ListNode*> s2; ListNode* p=headA; ListNode* q=headB; while(p){ s1.push(p); p=p->next; } while(q){ s2.push(q); q=q->next; } ListNode* tmp1=NULL; ListNode* tmp2=NULL; int ok=0; ListNode* ans=NULL; while(!s1.empty()&&!s2.empty()){ tmp1=s1.top(); tmp2=s2.top(); s1.pop(); s2.pop(); if(tmp1!=tmp2){ return ans; } if(s1.empty()) return tmp1; if(s2.empty()) return tmp2; ans=tmp1; } return NULL; }};
0 0
- leetcode 160-Intersection of Two Linked Lists
- leetcode 160: Intersection of Two Linked Lists
- LeetCode(160) Intersection of Two Linked Lists
- [leetcode 160] Intersection of Two Linked Lists
- leetCode #160 Intersection of Two Linked Lists
- LeetCode(160) Intersection of Two Linked Lists
- LeetCode[160]Intersection of Two Linked Lists
- [LeetCode 160]Intersection of Two Linked Lists
- [LeetCode][160][Intersection of Two Linked Lists ]
- leetcode-160 Intersection of Two Linked Lists
- leetcode 160Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists
- leetcode[160]:Intersection of Two Linked Lists
- leetcode-160-Intersection of Two Linked Lists
- [Leetcode 160] Intersection of Two Linked Lists
- leetcode 160: Intersection of Two Linked Lists
- [Leetcode]#160 Intersection of Two Linked Lists
- LeetCode 160 Intersection of Two Linked Lists
- struts2框架搭建
- Meeting Rooms
- 编程中数据隐藏(一)
- org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginAction‘
- unity3d学习中的一些问题
- leetcode-Intersection of Two Linked Lists-160
- 欢迎使用CSDN-markdown编辑器
- maven pom.xml文件教程详解
- maven自动建立目录骨架
- 翻译之前的说明
- 树莓派学习系列5——使用python编写简单的游戏程序
- position2(转载)
- 行框
- maven全球中央仓库