链表的应用—从尾到头打印链表、复杂链表的复制

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

这题需要看题解的原因是,不知道如何表示节点不存在,以为不存在:head.val==None
循环的判断条件是当前节点,而不是head.next

# 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]:
        a = []
        # if head == None:
        # if head.val==None # AttributeError: 'NoneType' object has no attribute 'val'
        if not head:
            return a
        while head: #当前节点存在就进行操作
            a.append(head.val)
            head = head.next
        a = a[::-1]
        return a

剑指 Offer 24. 反转链表

还是画个图比直接写清楚

# 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:
        if not head:
            return head
        node1 = head.next
        node2 =None
        head.next = None # 放在循环外面
        while head and node1:
            node2 = node1.next
            node1.next = head
            head = node1
            node1 = node2
        return head




class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            tmp = cur.next # 暂存后继节点 cur.next
            cur.next = pre # 修改 next 引用指向
            pre = cur      # pre 暂存 cur
            cur = tmp      # cur 访问下一节点
        return pre

作者:jyd
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/jian-zhi-offer-24-fan-zhuan-lian-biao-die-dai-di-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

剑指 Offer 35. 复杂链表的复制

第一种方法就是遍历两次,先生成一条完整的序列,然后再补充链接
第二种方法就比较有意思,7-3-1-5-2的旧序列变成7-7-3-3-1-1-5-5-2-2
两种方法都值得去尝试。

#返回指定键的值,如果键不在字典中返回默认值 None 或者指定的默认值。
#dict.get(key, default=None)

"""
# 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':
        dic = {}
        cur = head
        if not cur:
            return cur
        while cur:
            dic[cur] = Node(cur.val)
            cur = cur.next
        cur = head
        while cur:
            if cur.next:
                dic[cur].next = dic[cur.next]
            if cur.random:
                dic[cur].random = dic[cur.random] # 如果cur.random == None就报错
            cur = cur.next
        return dic[head]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值