一:剑指 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的内存机制有点不清楚,第三题就很迷,最后看个思路,临摹了大佬的代码