python实现求两个链表的第一个交叉结点

方法一

两个有公共节点的链表自公共节点后是重合的。可以借助两个栈先存储链表的节点。然后两个栈每次出栈一个节点,如果是重合节点,那么这两个节点是相等的。所以最后一个相等的节点就是第一个公共节点。

方法二

先遍历两个链表,统计长度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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值