# LeetCode 160. 相交链表（C、C++、python）

A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3


C

/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
{
struct ListNode* h1=NULL;
struct ListNode* h2=NULL;
if(p==NULL || q==NULL)
{
return NULL;
}
else
{
int m=1,n=1;
while(p->next)
{
m++;
p=p->next;
}
while(q->next)
{
n++;
q=q->next;
}
if(p!=q)
{
return NULL;
}
else
{
if(m>n)
{
}
else
{
}
m=abs(m-n);
for(int i=0;i<m;i++)
{
h1=h1->next;
}
while(h1!=h2)
{
h1=h1->next;
h2=h2->next;
}
return h1;
}
}
}

C++

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
{
stack<ListNode*> s1;
stack<ListNode*> s2;
if(p==NULL || q==NULL)
{
return NULL;
}
while(p)
{
s1.push(p);
p=p->next;
}
while(q)
{
s2.push(q);
q=q->next;
}
ListNode* res=NULL;
while(!s1.empty() && !s2.empty() && s1.top()==s2.top())
{
res=s1.top();
s1.pop();
s2.pop();
}
return res;
}
};

python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
if p==None or q==None:
return None
else:
m=1
n=1
while p.next:
m += 1
p=p.next
while q.next:
n += 1
q=q.next
if p!=q:
return None
else:
m=m-n
if m>0:
else:
return h1