算法第三周作业03
来源:互联网 发布:淘宝怎么输入链接 编辑:程序博客网 时间:2024/05/20 07:59
Description
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
Solution
1. 对于第一组[0,k],可以从0开始读节点node,另外在一个新链表head里面写,node.next = head, head = node,从而实现倒序;
2. 使用递归方式对接下来的分组[k+1, 2k],[2k+1, 3k]...进行处理;
3. 首先需要读取输入链表的长度,然后判断需要倒序的组数;
Code
public ListNode reverseKGroup(ListNode head, int k) {ListNode oldHead = head;int count = 0;// 获取输入链表的长度,得到需要递归的次数while(head != null){head = head.next;count++;}return recursion(oldHead, k, count/k);}public ListNode recursion(ListNode head, int k, int times){if(head != null && times != 0){ListNode oldHead = head;ListNode node1 = head;ListNode node2 = head.next;int i = 0;head = null;// 读取输入链表// 倒序写入输出链表while (i++ < k && node1 != null) {node1.next = head;head = node1;node1 = node2;if(node1 != null)node2 = node2.next;}// 递归操作接下来的节点oldHead.next = recursion(node1, k, times-1);}return head;}
0 0
- 算法第三周作业03
- 第三周算法作业
- 算法概论第三周作业
- 第三周作业 算法概论
- 算法第三周作业02
- 算法第三周作业01
- 算法概论第三周作业:冒泡排序
- 普林斯顿算法课第三周作业
- 算法作业_5(2017.3.7第三周)
- 算法作业_6(2017.3.11第三周)
- 算法课第三周作业 | Subsets
- 第三周算法作业冒泡排序1114班
- 算法设计与应用基础作业第三周
- 算法课程Leetcode作业第三周技术博客
- 算法分析与设计课程作业第三周#1
- 第三周作业
- 第三周作业 2
- 第三周作业 3
- 【学习笔记】python读取json内容转换成excel格式
- HTML5 初学者一步一步攀爬 努力加油学习
- windbg的chksym命令
- C++复习2
- 关于动态规划问题
- 算法第三周作业03
- 用BitBlt截取整屏后半透明窗口不能显示的解决办法
- 深入浅出JMS(三)--ActiveMQ简单的HelloWorld实例
- MySQL性能调优
- adb logcat 命令行用法
- Android Notification不显示浮动通知,不显示锁屏通知
- 在屏幕上打印是非常消耗计算资源的一种做法
- 自己开发的JAVA SE版本的小游戏
- 易语言网络验证防破解教程