一【题目类别】
二【题目难度】
三【题目编号】
四【题目描述】
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
五【题目示例】
示例 1: 输入:head = [1,2,3,4,5], k = 2 输出:[2,1,4,3,5] 示例 2: 输入:head = [1,2,3,4,5], k = 3 输出:[3,2,1,4,5] 示例 3: 输入:head = [1,2,3,4,5], k = 1 输出:[1,2,3,4,5] 示例 4: 输入:head = [1], k = 1 输出:[1]
六【题目提示】
列表中节点的数量在范围 sz 内 1 <= sz <= 5000 0 <= Node.val <= 1000 1 <= k <= sz
七【题目进阶】
你可以设计一个只使用常数额外空间的算法来解决此问题吗? 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
八【解题思路】
这道题的难点在于空间复杂度复杂度要求常数级别,但是最简单的方法就是用栈,但是栈的空间复杂度肯定不是常数级别的,题解递归用得很多,但我觉得递归的空间复杂度也不是常数级别,所以用迭代的方法,每次找到k个链表,然后将这一部分反转再链接到原来的链表中
九【时间频度】
十【代码实现】
Java语言版
package LinkedList;
import java. util. Stack;
public class p25_ReverseNodesInKGroup {
int val;
p25_ReverseNodesInKGroup next;
p25_ReverseNodesInKGroup ( int x) {
this . val = x;
}
public static void main ( String[ ] args) {
p25_ReverseNodesInKGroup num1 = new p25_ReverseNodesInKGroup ( 1 ) ;
p25_ReverseNodesInKGroup num2 = new p25_ReverseNodesInKGroup ( 2 ) ;
p25_ReverseNodesInKGroup num3 = new p25_ReverseNodesInKGroup ( 3 ) ;
p25_ReverseNodesInKGroup num4 = new p25_ReverseNodesInKGroup ( 4 ) ;
p25_ReverseNodesInKGroup num5 = new p25_ReverseNodesInKGroup ( 5 ) ;
num1. next = num2;
num2. next = num3;
num3. next = num4;
num4. next = num5;
int k = 2 ;
p25_ReverseNodesInKGroup res = reverseKGroup ( num1, k) ;
while ( res != null) {
System. out. print ( res. val + " " ) ;
res = res. next;
}
}
public static p25_ReverseNodesInKGroup reverseKGroup ( p25_ReverseNodesInKGroup head, int k) {
Stack< p25_ReverseNodesInKGroup> stack = new Stack < p25_ReverseNodesInKGroup> ( ) ;
p25_ReverseNodesInKGroup newHead = new p25_ReverseNodesInKGroup ( Integer. MIN_VALUE) ;
newHead. next = head;
p25_ReverseNodesInKGroup pre = newHead;
while ( true ) {
int count = 0 ;
p25_ReverseNodesInKGroup temp = head;
while ( temp != null && count < k) {
stack. push ( temp) ;
temp = temp. next;
count++ ;
}
if ( count != k) {
pre. next = head;
break ;
}
while ( ! stack. isEmpty ( ) ) {
pre. next = stack. pop ( ) ;
pre = pre. next;
}
pre. next = temp;
head = temp;
}
return newHead. next;
}
}
C语言版
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct ListNode
{
int val;
struct ListNode * next;
} ;
struct ListNode* reverseKGroup ( struct ListNode* head, int k)
{
struct ListNode newHead = { 0 } ;
newHead. next = head;
struct ListNode* pre = NULL ;
pre = & newHead;
struct ListNode* * stack = ( struct ListNode * * ) malloc ( sizeof ( struct ListNode * ) * k) ;
memset ( stack, 0 , sizeof ( struct ListNode * ) * k) ;
while ( true)
{
int count = 0 ;
struct ListNode* temp = head;
while ( temp != NULL && count < k)
{
stack[ count] = temp;
temp = temp-> next;
count++ ;
}
if ( count != k)
{
pre-> next = head;
break ;
}
while ( count > 0 )
{
pre-> next = stack[ count - 1 ] ;
pre = pre-> next;
count-- ;
}
pre-> next = temp;
head = temp;
}
return newHead. next;
}
十一【提交结果】
Java语言版 C语言版