25. K 个一组翻转链表
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
栈:
用栈,我们把k个数压入栈中,然后弹出来的顺序就是翻转的!
这里要注意几个问题
第一,剩下的链表个数够不够k个(因为不够k个不用翻转);
第二,已经翻转的部分要与剩下链表连接起来
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def reverseKGroup(self, head: ListNode, k: int) -> ListNode:dummy = ListNode(0)p = dummywhile True:count = kstack = []tmp = headwhile count and tmp:stack.append(tmp)tmp = tmp.nextcount -= 1# 注意,目前tmp所在k+1位置# 说明剩下的链表不够k个,跳出循环if count :p.next = headbreak# 翻转操作while stack:p.next = stack.pop()p = p.next#与剩下链表连接起来p.next = tmphead = tmpreturn dummy.next
递归:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def reverseKGroup(self, head: ListNode, k: int) -> ListNode:cur = headcount = 0while cur and count < k:cur = cur.nextcount += 1# 此时cur指向第k+1个if count == k:cur = self.reverseKGroup(cur, k)while count:tmp = head.next # head指向本轮待排序,tmp指向下一个待排序head.next = cur # 将待排序的开头与排好序相接cur = head # 此时cur指向后端已排好序的开头head = tmp # head指向待排序的开头count -= 1head = curreturn head
