class ListNode:
def __init__(self, val=0, next= node):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
pre = None
cur = head
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
return pre
class Solution:
def reverseBetween(self, head, left, right):
p0 = dummy = ListNode(next = head) # 这样一起实例化,p0和dummy永远都是指向同一位置
for _ in range(left-1):
p0 = p0.next # 知道转换的前一个结点
pre = None
cur = p0.next # 当前正在处理的节点
for _ in range(right-left+1)
nxt = cur.next
cur.nxt = pre
pre = cur
cur = nxt
p0.next.next = cur
p0.next = pre
return dummy.next
代码:
python复制代码
class Solution:
def reverseKGroup(self, head, k):
n = 0
cur = head
while cur:
n += 1
cur = cur.next
p0 = dummy = ListNode(next = head)
pre = None
cur = head
# k个一组处理
while n >= k:
n -= k
for _ in range(k):
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
nxt = p0.next
nxt.next = cur
p0.next = pre
p0 = nxt
二、148. 排序链表
2.1、876. 链表的中间结点
代码:这道题典型的快慢指针
python复制代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
t1 = t2 = head
while t2 and t2.next:
t1 = t1.next
t2 = t2.next.next
return t1
2.2、21. 合并两个有序链表
代码:
python复制代码
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
cur = dummy
while list1 and list2:
if list1.val <= list2.val:
cur.next = list1
cur = cur.next
list1 = list1.next
else:
cur.next = list2
cur = cur.next
list2 = list2.next
if list1:
cur.next = list1
else:
cur.next = list2
return dummy.next