Leetcode 25/24 - Reverse Nodes in k-Group
题目描述
Leetcode 24 题主要考察的链表的反转,而 25 题是 24 的拓展版,加上对递归的考察。
对题目做一下概述:
提供一个链表,给定一个正整数 k, 每 k 个节点一组进行翻转,最后返回翻转后的新链表。
k 的值小于或等于链表的长度,如果节点总数不是 k 的整数倍,将最后一组剩余的节点保持原有顺序。
注意:
- 算法只能使用常数的空间
- 不能单纯的改变节点内部的值,需要进行节点交换。
举例:
Example:
Given 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
Given 1->2.
For k = 2, you should return: 2->1
For k = 3, you should return: 1->2
解题思路
主要考察来了我们对链表的反转已经递归思想的熟悉度。
对链表反转时,可以借助三个指针,pre,current,next
- pre 表示被翻转节点的前一个节点
- current 表示正在被翻转的节点
- next 表示正在被翻转的下一个节点

每次翻转时:
- next 指向 current 的下一个
- current 的 next 指向 prev
- 同时 current 和 prev 向前一步
在每次翻转后:
- current 表示下一个需要被翻转组中的第一个节点
- prev 表示当前翻转后的新链表头
- 原来的头 head 成了被翻转组中的尾节点
递归的处理
首先看到 K 个一组,想到到局部处理,并且局部处理翻转的方式是一致的,自然联想到递归。
递归的出口就是,被翻转后的新链表头或者未满足条件无需翻转的链表头。
代码实现:
# Question: Reverse Nodes in k-Group
# 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.
# Example:
# Given 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
# Note:
# Only constant extra memory is allowed.
# You may not alter the values in the list's nodes, only nodes itself
# may be changed.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
# check if head is NULL List
if head is None or head.next is None:
return head
# get the number of nodes
list_length = 0
new_head = head
while new_head is not None:
list_length += 1
new_head = new_head.next
# If the length of nodes is less than the number of group
if list_length < k:
return head
# calculate the number of groups that can be reversed
number_of_groups = int(list_length / k)
return self.swapPairs(head, k, number_of_groups)
def swapPairs(self, head: ListNode, k, number_of_groups, number_of_reversed_groups=0) -> ListNode:
prev = None
current = head
n = k
# reverse the node due to the count of n
# After the reversal is completed,
# prev is the new head of the group that has been reversed.
# current points the head of the next group to be processed.
# head is the new end of the group that has been reversed.
while current and n > 0:
n -= 1
next = current.next
current.next = prev
prev = current
current = next
# after a group of nodes is reversed, then increase 1.
number_of_reversed_groups += 1
# determine whether to reverse the next group
if current is not None and number_of_reversed_groups < number_of_groups:
head.next = self.swapPairs(
current, k, number_of_groups, number_of_reversed_groups)
else:
head.next = current
return prev
def print_list_node(self, head: ListNode):
result = ''
while head is not None:
result += str(head.val) + '->'
head = head.next
print(result.rstrip('->'))
if __name__ == '__main__':
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
solution = Solution()
solution.print_list_node(l1)
reversed_l1 = solution.reverseKGroup(l1, 2)
solution.print_list_node(reversed_l1)
Leetcode 25/24 - Reverse Nodes in k-Group的更多相关文章
- [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 ...
- Reverse Nodes In K Group,将链表每k个元素为一组进行反转---特例Swap Nodes in Pairs,成对儿反转
问题描述:1->2->3->4,假设k=2进行反转,得到2->1->4->3:k=3进行反转,得到3->2->1->4 算法思想:基本操作就是链表 ...
- 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
[LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...
- [Leetcode][Python]24: Swap Nodes in Pairs
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 24: Swap Nodes in Pairshttps://oj.leetc ...
- 【LeetCode】24. Swap Nodes in Pairs (3 solutions)
Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. For exam ...
- LeetCode解题报告—— Reverse Nodes in k-Group && Sudoku Solver
1. Reverse Nodes in k-Group Given a linked list, reverse the nodes of a linked list k at a time and ...
- LeetCode OJ:Reverse Nodes in k-Group(K个K个的分割节点)
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If ...
- 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 list. ...
- [leetcode]算法题目 - Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If ...
随机推荐
- c++异常处理的方法
c++异常处理 程序运行时常会碰到一些异常情况,例如:做除法的时候除数为 0:用户输入年龄时输入了一个负数:用 new 运算符动态分配空间时,空间不够导致无法分配:访问数组元素时,下标越界:打开文件读 ...
- selenium驱动chrome浏览器问题
selenium是一个浏览器自动化测试框架,以下介绍其如何驱动chrome浏览器? 1.下载与本地chrome版本对应的chromedriver.exe ,下载地址为http://npm.taobao ...
- EFK教程 - EFK快速入门指南
通过部署elasticsearch(三节点)+filebeat+kibana快速入门EFK,并搭建起可用的demo环境测试效果 作者:"发颠的小狼",欢迎转载与投稿 目录 ▪ 用途 ...
- 你不知道的DIV+CSS的命名规则
搜索引擎优化(seo)有很多工作要做,其中对代码的优化是一个很关键的步骤.为了更加符合SEO的规范,下面是目前比较好的CSS+DIV的命名规则 1DIV CLASS或者ID 页头:header 登录条 ...
- ThingJS和传统3D开发的区别
物联网3D可视化开发已经辐射到各行各业,无论车间还是消防,城市还是粮仓,亦或是地铁.科技园,物联网可视化是科技的进步,也是行业的进步.而传统的3D可视化开发实施起来并不那么乐观.如果使用ThingJS ...
- 在树莓派上安装Theano
“查遍全网都没人成功在树莓派安装Theano,这是什么样的感觉?” ——写在开头 在这里必须先说一下,由于安装过程中的坑太多了,遇到的问题层出不穷,所以我这里只能记录我安装过程中的印象深刻的问题,如果 ...
- Java ArrayList底层实现原理源码详细分析Jdk8
简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用 ...
- linux(CentOS release 6.5)环境搭建svn
正文之前,说几句关于svn和git的闲话. 之前用的版本控制工具主要都是svn,随着时间的推移,git以其强大灵活的分支管理功能受到大众喜爱.尤其是多人同时开发时同一项目,且不同部分功能时,git的分 ...
- 学习笔记33_EF跨数据库
在App.Config中,可以: (1)自定义类 public xxxxDbContext() { public XXXXDbContext():base("name=xxxxContain ...
- C函数库errno.h概况
在linux中使用c语言编程时,errno是个很有用的动动.他可以把最后一次调用c的方法的错误代码保留.但是如果最后一次成功的调用c的方法,errno不会改变.因此,只有在c语言函数返回值异常时,再检 ...