python编程练习---2023年1月16日

一:剑指 Offer 06. 从尾到头打印链表

难度简单364

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
        self.alist=[]
        ahead=head
        while ahead:
            self.alist.append(ahead.val)
            ahead=ahead.next
        self.alist.reverse()
        return self.alist
二:剑指 Offer 24. 反转链表

难度简单523

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        # 使用头插法进行建表
        self.ahead=ListNode(None)
        while head:
            bhead=ListNode(head.val)
            bhead.next=self.ahead.next
            self.ahead.next=bhead
            head=head.next

        return self.ahead.next
三:剑指 Offer 35. 复杂链表的复制

难度中等642

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head: 
            return None
        
        cur=head
        while cur:
            tmp=cur.next
            cur.next=Node(cur.val)
            cur.next.next=tmp
            cur=tmp

        cur=head
        while cur:
            if cur.random:
                cur.next.random=cur.random.next
            cur=cur.next.next
        
        ret=head.next
        tmp=head.next
        while tmp.next:
            head.next=head.next.next
            head=head.next
            tmp.next=tmp.next.next
            tmp=tmp.next

        return ret


        # 评论区看到的绝妙方法
        # import copy
        # return copy.deepcopy(head)

没深入学python,对python的内存机制有点不清楚,第三题就很迷,最后看个思路,临摹了大佬的代码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惜日短

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值