Reverse Nodes in k-Group
来源:互联网 发布:网络培训班 编辑:程序博客网 时间:2024/06/15 10:33
这道题让自己做了很久,光是草稿纸画图,就用了3页。但我们觉得这是值得的!我们必须得有认真钻研的劲头,必须要搞得明明白白,不留死角。
当中颠倒顺序的做法同之前的模板有不同。
之前的是颠倒整个(子)list的顺序,不用考虑之后的链接。
而这个是颠倒list中间一部分的顺序,必须要考虑整个list的链接。
方法当中的prev和next是边界,不参与顺序颠倒,last是最开始要参与颠倒的节点,也是最后要返回的节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (head == null || k <= 1) { return head; } ListNode dummy = new ListNode(0); ListNode node = head; ListNode prev = dummy; dummy.next = head; int count = 0; while (node != null) { count++; ListNode next = node.next; if (count == k) { prev = reverseNode(prev, next); count = 0; } node = next; } return dummy.next; } private ListNode reverseNode(ListNode prev, ListNode next) { ListNode last = prev.next; ListNode cur = last.next; while (cur != next) { last.next = cur.next; cur.next = prev.next; prev.next = cur; cur = last.next; } return last; } }
0 0
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- angular2 quickstart
- listview与ScrollView冲突的解决办法
- iOS Provisioning Profile(Certificate)与Code Signing详解
- UVa 512 Spreadsheet Tracking
- iOS开发问题之:此Apple ID尚未在iTunes Store使用过......
- Reverse Nodes in k-Group
- Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等
- Android模拟后台进程被杀
- 【VC小项目】-13.2形状类族的中的纯虚函数
- 欢迎使用CSDN-markdown编辑器
- Reactor模式详解
- qq分享时mainActivity的主要代码
- 【Objective-C基础】自定义对象归档
- 利用ContentProvider的添加数据