题目描述
输入两个链表,找出它们的第一个公共结点。
思路
暴力:用一个stack来存储
改进:对于两个链表而言,第一个相遇节点后的所有所有节点都是相同,因为node只有一个next。
先获取两个链表的长度,然后用要一对快慢指针
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, head1, head2):
len1 = 0
len2 = 0
start1 = head1
start2 = head2
while head1:
len1+=1
head1 = head1.next
while head2:
len2+=1
head2 = head2.next
if len2>len1:
for i in range(len2-len1):
start2 = start2.next
elif len1>len2:
for i in range(len1-len2):
start1 = start1.next
while start1 and start2:
if start1==start2:
return start1
start1 = start1.next
start2 = start2.next
return None