LeetCode(6)
来源:互联网 发布:淘宝客订单部分退款 编辑:程序博客网 时间:2024/06/05 20:43
https://leetcode.com/problems/reverse-nodes-in-k-group/#/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:
本题的重点在于每k个数进行reverse,所以我们可以用遍历的方法。
- 当当前的head满足k的条件时,将head的第k个next作为输入,进行下一次求解。
- 当当前head不满足k的条件时,则直接返回head。
- 在获得某次递归的返回后,则单独进行k的reverse。
代码如下:
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; }}public ListNode reverseKGroup(ListNode head, int k) { int count = k; ListNode next = head; //检测剩余的ListNode数 do { if(next != null) { next = next.next; } else { break; } } while (--count > 0); if(count == 0) { next = reverseKGroup(next, k); while (count++ < k) { //从前往后交换位置 ListNode temp = head.next; head.next = next; next = head; head = temp; } head = next; } return head;}
0 0
- LeetCode--6
- LeetCode(6)
- LEetCode(6)
- leetcode 6
- LeetCode(6)
- LeetCode 6 - ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- LeetCode(6)ZigZag Conversion
- Leetcode【6】:ZigZag Conversion
- [leetcode 6] ZigZag Conversion
- LeetCode 6 LRU Cache
- LeetCode 6 ZigZag Conversion
- LeetCode(6) ZigZag Conversion
- [Leetcode] 6 - ZigZag Conversion
- LeetCode 6:《ZigZag Conversion》
- [leetcode 6] ZigZag Conversion
- LeetCode | #6 ZigZag Conversion
- [leetcode] 6 ZigZag Conversion
- 优雅的使用Laravel之phpstorm配置
- coreseek分词配置
- 【C语言】优先级和求值顺序
- Queue Reconstruction by Height
- Genymotion ova文件下载过慢怎么办?
- LeetCode(6)
- C++抽象编程——STL实战(4)——计算集合的交集,并集及区别
- vagrant系列(1):使用vagrant在线/离线安装centos7
- 深入理解C++中public、protected及private用法
- Java基础回顾--String对象中常用的方法
- 作业4:杨辉三角&奇偶阶乘&数组平均数
- LeetCode98. Validate Binary Search Tree Add to List
- python 创建多级目录
- Maven项目中没有出错,但是项目有个红色的叉