方法一
两个有公共节点的链表自公共节点后是重合的。可以借助两个栈先存储链表的节点。然后两个栈每次出栈一个节点,如果是重合节点,那么这两个节点是相等的。所以最后一个相等的节点就是第一个公共节点。
方法二
先遍历两个链表,统计长度len1,len2。让长链表先走 | len1-len2 | 步,公共节点肯定是存在于后面部分中。然后再对两个链表遍历匹配,遇到的第一个相同节点就是公共节点。
法一代码:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 思路一
def FindFirstCommonNode1(self, pHead1, pHead2):
# write code here
if pHead1 is None or pHead2 is None:
return None
s1 = []
s2 = []
p1 = pHead1
p2 = pHead2
while p1 is not None:
s1.append(p1)
p1 = p1.next
while p2 is not None:
s2.append(p2)
p2 = p2.next
res = None
while len(s1) > 0 and len(s2) > 0:
v1 = s1.pop()
v2 = s2.pop()
if v1 == v2:
res = v1
else:
break
return res
法二代码:
class Node(object):
def __init__(self,val,next=None):
self.value=val
self.next=next
def get_length(head):
length=0
while head:
length+=1
head=head.next
return length
def get_first_node(head1,head2):
len1=get_length(head1)
len2=get_length(head2)
cur1=head1
cur2=head2
if len1>len2:
while len1-len2>0:
cur1=cur1.next
len1-=1
elif len1<len2:
while len2-len1>0:
cur2=cur2.next
len2-=1
else:
pass
while cur1 and cur2:
if cur1.value==cur2.value:
print(cur1.value)
return cur1.value
cur1=cur1.next
cur2=cur2.next
print('没有')
if __name__ == '__main__':
a = Node('a1', Node('a2', Node('c1', Node('c2', Node('c3'))))) # 构造不带头结点的链表:a1→a2→c1→c2→c3
b = Node('b1', Node('b2', Node('b3', Node('c1', Node('c2', Node('c3')))))) # 构造不带头结点的链表:b1→b2→b3→c1→c2→c3
get_first_node(a,b)