1.剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
# 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.A, self.B = [], []
while head:
self.A.append(head.val)
head = head.next
while self.A:
self.B.append(self.A.pop())
return self.B
看了别人的的评论后,看到利用python数组的特性,可以用return self.A[::-1],来直接倒序输出。
另一种递归算法很简洁:
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next) + [head.val] if head else []
参考来源:作者:Krahets,链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/5d8831/
2.剑指 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:
res = None
while head:
temp = head.next
head.next = res
res = head
head = temp
return res
3.剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
本题的难点在于新链表的random指针如何指向与原链表位置相同的节点。
自己没做出来,还是python的基础忘记太多了。
方法一:哈希表
"""
# 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
"""
#采用dic建立新旧链表的键值对
class Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if not head: return None
cur = head
dic = {}
while cur:
dic[cur] = Node(cur.val)
cur = cur.next
cur = head
while cur:
dic[cur].next = dic.get(cur.next)
dic[cur].random = dic.get(cur.random)
cur = cur.next
return dic[head]
方法二:建立原节点-新节点-原节点-新节点的拼接链表,再拆分
"""
# 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: 'Optional[Node]') -> 'Optional[Node]':
if not head: return None
cur = head
#组建拼接链表
while cur:
temp = Node(cur.val)
temp.next = cur.next
cur.next = temp
cur = temp.next
#传递random变量
cur = head
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
#将拼接链表重新拆分为两个表
cur = head
res,tmp = head.next,head.next
while res.next:
cur.next = res.next
res.next = res.next.next
res = res.next
cur = cur.next
cur.next = None
return tmp