25.K个一组翻转链表
题目链接
25. K 个一组翻转链表 - 力扣(LeetCode)
解题思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:n = 0cur = headwhile cur:n += 1#统计节点个数cur = cur.nextp0 = dummy = ListNode(next = head)pre = Nonecur = headwhile n >= k:n -= kfor _ in range(k):nxt = cur.nextcur.next = prepre = curcur = nxtnxt = p0.nextnxt.next = curp0.next = prep0 = nxtreturn dummy.next
138.随机链表的复制
题目链接
148. 排序链表 - 力扣(LeetCode)
解题思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:length = 0if head == None or head.next == None: return headcurrentNode = headvalues = []while currentNode:length += 1values.append(currentNode.val)currentNode = currentNode.nextvalues =sorted( values )currentNode = headi = 0while currentNode:currentNode.val = values[i] currentNode = currentNode.nexti += 1return head
146.LRU缓存
题目链接
146. LRU 缓存 - 力扣(LeetCode)
解题思路
class ListNode:def __init__(self, key=None, value=None):self.key = keyself.value = valueself.prev = Noneself.next = Noneclass LRUCache:def __init__(self, capacity: int):self.capacity = capacityself.hashmap = {}# 新建两个节点 head 和 tailself.head = ListNode()self.tail = ListNode()# 初始化链表为 head <-> tailself.head.next = self.tailself.tail.prev = self.head# 因为get与put操作都可能需要将双向链表中的某个节点移到末尾,所以定义一个方法def move_node_to_tail(self, key):# 先将哈希表key指向的节点拎出来,为了简洁起名node# hashmap[key] hashmap[key]# | |# V --> V# prev <-> node <-> next pre <-> next ... nodenode = self.hashmap[key]node.prev.next = node.nextnode.next.prev = node.prev# 之后将node插入到尾节点前# hashmap[key] hashmap[key]# | |# V --> V# prev <-> tail ... node prev <-> node <-> tailnode.prev = self.tail.prevnode.next = self.tailself.tail.prev.next = nodeself.tail.prev = nodedef get(self, key: int) -> int:if key in self.hashmap:# 如果已经在链表中了久把它移到末尾(变成最新访问的)self.move_node_to_tail(key)res = self.hashmap.get(key, -1)if res == -1:return reselse:return res.valuedef put(self, key: int, value: int) -> None:if key in self.hashmap:# 如果key本身已经在哈希表中了就不需要在链表中加入新的节点# 但是需要更新字典该值对应节点的valueself.hashmap[key].value = value# 之后将该节点移到末尾self.move_node_to_tail(key)else:if len(self.hashmap) == self.capacity:# 去掉哈希表对应项self.hashmap.pop(self.head.next.key)# 去掉最久没有被访问过的节点,即头节点之后的节点self.head.next = self.head.next.nextself.head.next.prev = self.head# 如果不在的话就插入到尾节点前new = ListNode(key, value)self.hashmap[key] = newnew.prev = self.tail.prevnew.next = self.tailself.tail.prev.next = newself.tail.prev = new