网上看到两种方法:
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;
}
};
本文介绍两种寻找两个链表相交节点的方法:一种是通过计算链表长度来定位交点;另一种是使用栈来实现从后向前遍历查找。两种方法都需要遍历链表两次。
322

被折叠的 条评论
为什么被折叠?



