两个链表的第一个公共节点(两种解法)

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


解法1

使用栈,将两个链表的node保存在栈中,因为如果有公共节点说明next相同,则后面的节点都是相同的

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        stack1, stack2 = [], []
        if pHead1 == None or pHead2 == None:
            return None
        while pHead1:
            stack1.append(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            stack2.append(pHead2)
            pHead2 = pHead2.next
        print(stack1, stack2)
        while True:
            pop1 = stack1.pop()
            pop2 = stack2.pop()
            print(pop1, pop2)
            if pop1 != pop2:
                return None
            if stack1 == [] or stack2 == [] or stack1[len(stack1) - 1] != stack2[len(stack2) - 1]:
                return pop1

运行时间:32ms

占用内存:5752k


解法2

首先算出两个链表的长度,算出长度差值之后,长的链表先向后遍历这个差值,然后同步遍历。第一个相同的node就是解

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        if pHead1 == None or pHead2 == None:
            return None
        length1, length2 = 0, 0
        pNode1, pNode2 = pHead1, pHead2
        while pNode1:
            length1 += 1
            pNode1 = pNode1.next
        while pNode2:
            length2 += 1
            pNode2 = pNode2.next
        if length2 >= length1:
            differLength = length2 - length1
            while differLength:
                pHead2 = pHead2.next
                differLength -= 1
        else:
            differLength = length1 - length2
            while differLength:
                pHead1 = pHead1.next
                differLength -= 1
        while pHead1 != pHead2:
            pHead1 = pHead1.next
            pHead2 = pHead2.next
        return pHead1

运行时间:27ms

占用内存:5724k

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值