LeetCode(6) - Reverse Nodes in k-Group
2017-04-11 00:15
381 查看
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:
For k = 2, you should return:
For k = 3, you should return:
Solution:
本题的重点在于每k个数进行reverse,所以我们可以用遍历的方法。
当当前的head满足k的条件时,将head的第k个next作为输入,进行下一次求解。
当当前head不满足k的条件时,则直接返回head。
在获得某次递归的返回后,则单独进行k的reverse。
代码如下:
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; }
相关文章推荐
- LeetCode_Reverse Nodes in k-Group
- 链表-leetcode 25 Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- Reverse Nodes in k-Group leetcode
- leetcode 42: Reverse Nodes in k-Group
- Java [leetcode 25]Reverse Nodes in k-Group
- [Leetcode] Swap Nodes in Pairs & Reverse Nodes in k-Group
- [Leetcode 25] Reverse Nodes in k-Group
- leetcode-Reverse Nodes in k-Group
- leetcode:Reverse Nodes in k-Group
- leetcode 日经贴,Cpp code -Reverse Nodes in k-Group
- LeetCode2.2.9(Reverse Nodes in k-Group)
- LeetCode 25 Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- leetcode 25: Reverse Nodes in k-Group
- Reverse Nodes in k-Group k-group翻转链表@LeetCode
- [Leetcode] Reverse nodes in k group 每k个一组反转链表
- [LeetCode][Java] Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- Leetcode: Reverse Nodes in k-Group