题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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

这个题目花了蛮长时间,主要是没搞清楚逆转一个链表的关系。弄了半天。其实是蛮简单和经典的题目。

解法一:比较挫的解法。要判断很多分支,所以容易出错。先放在这里当反面教材。

 public static ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode firstGHead = head;
int idx = 0;
ListNode pp = null;
while(head != null) {
ListNode c = head;
if(k <= 1 || c == null)return firstGHead;
for(int i = 0; i < k - 1&& c != null;i++) {
c = c.next;
}
if(c == null) break;
c = head;//save original head
int i = k - 1;
ListNode p = head;
ListNode pn = p.next;
ListNode lastEnd = pp;
while(i > 0){
p = head;
head = head.next;
pn = p.next;
pp = lastEnd;
int swap = 0;
while(swap < i){
p.next = pn.next;
pn.next = p;
if(pp != null)
pp.next = pn;
pp = pn;
pn= p.next;
swap++;
}
i--;
}
if(idx++ == 0) firstGHead = head;
head = c.next;
pp = c;
}
return firstGHead;

逆转那部分惨不忍睹啊。。。虽然过了leetcode,但是很不simple。还有,如果写成递归leetcode是不让你过的。

解法二:比较好的解法,又是leetcode讨论组的人做的。首先,搞清楚怎么逆转一个单链表。其实O(n)就可以了。第一个肯定是last one。然后我们每遍历到一个node,就把它放到最链表的首位,最后一个么,最后就成为第一个了。下面是一个简单逆转链表的程序。

 ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head.next;
ListNode last = head;
while(cur != null){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
head = dummy.next;

reverse a linked list with a head node

因为有“放到链表首位”的操作,我们需要一个dummy的头节点,遇到的新节点我们simply state: pre.next = cur; 保持一个invariant就是last节点始终在最后(cur的前面一个)

然后我们有如下方法:

/**
* Reverse a link list between pre and next exclusively
* an example:
* a linked list:
* 0->1->2->3->4->5->6
* | |
* pre next
* after call pre = reverse(pre, next)
*
* 0->3->2->1->4->5->6
* | |
* pre next
* @param pre
* @param next
* @return the reversed list's last node, which is the precedence of parameter next
*/
private static ListNode reverse(ListNode pre, ListNode next){
ListNode last = pre.next;//where first will be doomed "last"
ListNode cur = last.next;
while(cur != next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
return last;
}

reverse range

就是区间的reverse。因为题目要求的是k group逆转嘛。注意人返回的是最后一个(last)节点,这样下一个k-group就可以用上了。牛人的想法真是周到体贴~~。主方法里面,遍历的过程中每次都计数,每次到达k个节点,就可以使用pre和head.next调用上面的方法逆转了。给跪了。

 public static ListNode reverseKGroup2(ListNode head, int k) {
if(head == null || k == 1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
int i = 0;
while(head != null){
i++;
if(i % k ==0){
pre = reverse(pre, head.next);
head = pre.next;
}else {
head = head.next;
}
}
return dummy.next;
}

reverseKGroup

通过这道题,我们学会了:

有效的算法是简洁的!简洁的!!简洁的!!!

LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]的更多相关文章

  1. [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 ...

  2. 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 算法思想:基本操作就是链表 ...

  3. leetcode第24题--Reverse Nodes in k-Group

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

  4. sql server 关于表中只增标识问题 C# 实现自动化打开和关闭可执行文件(或 关闭停止与系统交互的可执行文件) ajaxfileupload插件上传图片功能,用MVC和aspx做后台各写了一个案例 将小写阿拉伯数字转换成大写的汉字, C# WinForm 中英文实现, 国际化实现的简单方法 ASP.NET Core 2 学习笔记(六)ASP.NET Core 2 学习笔记(三)

    sql server 关于表中只增标识问题   由于我们系统时间用的过长,数据量大,设计是采用自增ID 我们插入数据的时候把ID也写进去,我们可以采用 关闭和开启自增标识 没有关闭的时候 ,提示一下错 ...

  5. 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. ...

  6. LeetCode 笔记系列 18 Maximal Rectangle [学以致用]

    题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...

  7. LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]

    题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...

  8. LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]

    题目:Given n non-negative integers representing an elevation map where the width of each bar is 1, com ...

  9. LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]

    题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...

随机推荐

  1. 使用 JavaScript 实现灵活的固定导航功能

    如果你想在网页中实现灵活的固定导航功能,那么 Smart Fixed Navigation 这个 JavaScript 小脚本可以帮助轻松实现一个固定的导航,让用户在访问你的网站的时候可以随时使用菜单 ...

  2. MySQL之MySQL5.7中文乱码

    自己的MySQL服务器不能添加中文,于是自己使用 show variables like 'character%'; 查看了当前的编码格式 我又通过以下方法将其设置为utf-8 SETcharacte ...

  3. C#各种数组直接的数据复制/转换

    之前做Opengl程序,用的的C#的SharpGL这个库,里面有各种奇怪绑定的函数,比如原型为: void glInterleavedArrays(uint format, int stride, v ...

  4. PHP代码审计中你不知道的牛叉技术点

    一.前言 php代码审计如字面意思,对php源代码进行审查,理解代码的逻辑,发现其中的安全漏洞.如审计代码中是否存在sql注入,则检查代码中sql语句到数据库的传输 和调用过程. 入门php代码审计实 ...

  5. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q49-Q51)

    Question 49You are designing a SharePoint 2010 intranet site for a corporation. Your design must mee ...

  6. 需要记住的几个ASCII码

    --------- A--------- a---------

  7. Python语法基础

    # coding=utf-8import random teacher = (1 < 3) and (2 > 5)print (teacher) index = random.randin ...

  8. 【Android】Vitamio 4.0 正式版发布/ Vitamio IOS 测试版发布(2013-07-16)

    一.链接 Vitamio官网:http://www.vitamio.org/ 官网github地址:https://github.com/yixia 自己无法编译通过的这里下载: Vitamio 4. ...

  9. 【原】Mac下统计任意文件夹中代码行数的工具——cloc

    这里介绍一个Mac系统统计代码行数的工具cloc. 1.首先,安装homebrew,已安装的请跳过. 打开终端工具Terminal,输入下列命令.过程中会让你按RETURN键以及输入mac桌面密码,按 ...

  10. #一周五# win10通用平台,无处不在的Xamarin,msbuild开源,MVP卢建晖的Asp.NET 5系列 (视频)

    又到周五,本周博主的大部分时间都花在深圳了.最近winhec的消息太多了,我只想补充一点,就是winhec时隔7年之后回归,大多数的媒体都还在沿用之前的“硬件工程大会(Hardware Enginee ...