剑指offer(14)两个链表的公共节点——python

题目描述
输入两个链表,找出它们的第一个公共结点。

首先弄明白,两个链表的公共节点是什么。是pHead1和pHead2在某个节点都指向了同一个节点。

方法1.

#用栈的方法(剑指offer书上的方法)
#构建两个栈,相当于将链表的顺序反过来,这样,两个链表最后一个不相同的节点,就是第一个公共节点。
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        if not pHead1 or not pHead2:
            return
        stack1 = []
        stack2 = []
        
        while pHead1 != None:
            stack1.append(pHead1)
            pHead1 = pHead1.next
        while pHead2 != None:
            stack2.append(pHead2)
            pHead2 = pHead2.next
        first = None
        while stack1 and stack2:
            top1 = stack1.pop()
            top2 = stack2.pop()
            if top1 is top2:
                first = top1
            else:
                break
        return first

方法2.
方法1利用栈主要解决就是同时到达第一个结点的问题。
从链表头出发如何同时到达第一个相同的结点.
链表的长度相同就可以,其实就是走的结点数目相同。所以可以让其中长的链表先走几步,剩余的长度到短链表的长度相同。

#将长度长的链表的前面部分删除
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, head1, head2):
        if not head1 or not head2:
            return None
 
        p1, p2= head1, head2
        length1 = length2 = 0
 
        while p1:
            length1 += 1
            p1 = p1.next
        while p2:
            length2 += 1
            p2 = p2.next
 
        if length1 > length2:
            while length1 - length2:
                head1 = head1.next
                length1 -= 1
        else:
            while length2 - length1:
                head2 = head2.next
                length2 -= 1
 
        while head1 and head2:
            if head1 is head2:
                return head1
            head1 = head1.next
            head2 = head2.next
 
        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值