【LeetCode 面试经典150题】25. Reverse Nodes in k-Group K个一组翻转链表

本文介绍了一种算法,如何给定一个链表和一个整数k,每次反转k个节点后返回新的链表。使用迭代方法处理,确保在O(1)额外空间内完成,且处理链表边界条件和剩余节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

25. Reverse Nodes in k-Group

题目大意

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

中文释义

给定一个链表的头节点,每次反转 k 个节点,并返回修改后的链表。

k 是一个正整数,且小于或等于链表的长度。如果节点数不是 k 的倍数,则最后剩下的节点应保持原样。

你不能更改链表节点中的值,只能更改节点本身。

示例

Example 1:
在这里插入图片描述

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:
在这里插入图片描述

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

限制条件

  • 链表中的节点数为 n。
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

进阶问题

你能在 O(1) 额外内存空间中解决这个问题吗?

解题思路

方法

即在给定的单链表中每 k 个节点为一组进行反转。该方法使用迭代方式。

  1. 边界条

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值