剑指 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]