题目

Given a linked list, reverse the nodes of a linked list k at a time and return its 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 nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

翻译

相比 swap in pairs,这道题是每满 k 个进行一次倒转,如果最终不满 k 个则不进行倒转

Hints

Related Topics: Linked List

solution

可以利用递归,递归函数传入 head 和 k,和 swap in pairs 一样,只是先对 k 个进行判断,看是否到达链表的最后,如果是最后 k-1 个(或者少于k-1),则不进行倒转,返回 head;然后对由 head 开始的 k 个 Node 组成的小链表进行倒转就好了,倒转可以参考 看图理解单链表的反转 只不过 head.next 不指向 null,而是指向递归的 reverseKGroup(end,k) (end 是 head 之后的第 k+1 个)

如果不利用递归其实也是一样的,只不过把递归的过程用 while 循环写出来,每到可以整除 k 的时候进行一次倒转

代码

Java

//without recursion
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode begin;
if (head==null || head.next ==null || k==1)
return head;
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
begin = dummyhead;
int i=0;
while (head != null){
i++;
if (i%k == 0){
begin = reverse(begin, head.next);
head = begin.next;
} else {
head = head.next;
}
}
return dummyhead.next;
}
public ListNode reverse(ListNode begin, ListNode end){
ListNode curr = begin.next;
ListNode next, first;
ListNode prev = begin;
first = curr;
while (curr!=end){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
begin.next = prev;
first.next = curr;
return first;
}
} //solution in discuss
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// head - head-pointer to direct part,
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
head.next = curr; // preappending "direct" head to the reversed list
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
head = curr;
}
return head;
}
}

Python

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tmp = head
if k<=1:
return head
for i in range(k):
if tmp!=None:
tmp = tmp.next
else:
return head
p = head
q = head.next
r = None
head.next = self.reverseKGroup(tmp,k)
while q!=tmp:
r = q.next
q.next = p
p = q
q = r
head = p
return head

蜗牛慢慢爬 LeetCode 25. Reverse Nodes in k-Group [Difficulty: Hard]的更多相关文章

  1. 蜗牛慢慢爬 LeetCode 7. Reverse Integer [Difficulty: Easy]

    题目 Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Have ...

  2. 蜗牛慢慢爬 LeetCode 3. Longest Substring Without Repeating Characters [Difficulty: Medium]

    题目 Given a string, find the length of the longest substring without repeating characters. Examples: ...

  3. Leetcode 25. Reverse Nodes in k-Group 以每组k个结点进行链表反转(链表)

    Leetcode 25. Reverse Nodes in k-Group 以每组k个结点进行链表反转(链表) 题目描述 已知一个链表,每次对k个节点进行反转,最后返回反转后的链表 测试样例 Inpu ...

  4. LeetCode 25 Reverse Nodes in k-Group Add to List (划分list为k组)

    题目链接: https://leetcode.com/problems/reverse-nodes-in-k-group/?tab=Description   Problem :将一个有序list划分 ...

  5. [Leetcode] Reverse nodes in k group 每k个一组反转链表

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

  6. [LeetCode] 25. Reverse Nodes in k-Group 每k个一组翻转链表

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

  7. [leetcode 25]Reverse Nodes in k-Group

    1 题目: Given a linked list, reverse the nodes of a linked list k at a time and return its modified li ...

  8. Java [leetcode 25]Reverse Nodes in k-Group

    题目描述: Given a linked list, reverse the nodes of a linked list k at a time and return its modified li ...

  9. [leetcode]25. Reverse Nodes in k-Group每k个节点反转一下

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

随机推荐

  1. 1008. [HNOI2008]越狱【快速幂】

    Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果 相邻房间的犯人的宗教相同,就可能发生越狱,求有多少种状态可能发生越狱 I ...

  2. 随手练——小米OJ 高弗雷勋爵

    高弗雷勋爵 题目链接:https://code.mi.com/problem/list/view?id=113 这个解法比较暴力,主要需要注意的是一颗子弹 弹死两个及以上的情况. #include & ...

  3. ORACLE RMAN备份及还原(转)

    RMAN可以进行增量备份:数据库,表空间,数据文件 只有使用过的block可以被备份成backup set 表空间与数据文件对应关系:dba_data_files / v$datafile_heade ...

  4. 开源http协议库curl和wget的区别和使用

    curl和wget基础功能有诸多重叠,如下载等. 在高级用途上的curl由于可自定义各种请求参数所以长于模拟web请求,用于测试网页交互(浏览器):wget由于支持ftp和Recursive所以长于下 ...

  5. Publisher和Subscriber节点

    一.Publisher节点 /*"ros/ros.h"里面包含了ROS系统内最常用的一些头文件,包含此文件,便可以使用ROS的核心功能.*/#include "ros/r ...

  6. python+jenkins 构建节点环境编译器配置问题

    python 编译器默认添加环境变量路径 

  7. HDU1863(Kruskal+并查集水题)

    https://cn.vjudge.net/problem/HDU-1863 省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可). ...

  8. P3195 [HNOI2008]玩具装箱TOY

    列出DP方程式:设f[i]表示分组完前i件物品的最小花费,为方便计算,设sum[i]表示是前i件物品的长度和. f[i]=min(f[j]+(sum[i]-sum[j]+i-j-L-1)^2) [0& ...

  9. MongoDB 安装及副本集简单操作

    安装MongoDB 3.4 # 查看现有yum源 [root@localhost ~]# ll /etc/yum.repos.d/ total 36 -rw-r--r--. 1 root root 1 ...

  10. WPF之Manipulation

    原文:WPF之Manipulation 需求:现,在窗口下有一个StackPanel控件. 1.可以拖动. 2.可以展开及收缩(不仅仅可以拖动还可以点击) 3.窗口向坐标轴一样分四个象限,在不同的区域 ...