CODE 107: Reverse Nodes in k-Group
2013-11-04 20:19
295 查看
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:
For k = 2, you should return:
For k = 3, you should return:
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 ListNode reverseKGroup(ListNode head, int k) { // Start typing your Java solution below // DO NOT write main() function ListNode tmpHead = head; Stack<Integer> stack = new Stack<Integer>(); int number = 1; while (tmpHead != null) { ListNode tmp = tmpHead; while (tmp != null && number <= k) { stack.push(tmp.val); tmp = tmp.next; number++; } if (number > k) { while (!stack.isEmpty()) { tmpHead.val = stack.pop(); tmpHead = tmpHead.next; } } tmpHead = tmp; number = 1; } return head; }
相关文章推荐
- lintcode:Reverse Nodes in k-Group
- leecode 解题总结:25 Reverse Nodes in k-Group
- Leet Code 25 Reverse Nodes in k-Group - Java
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group 解答
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- Leetcode: Reverse Nodes in k-Group
- LeetCode 128 Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- leetcode 25 Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- LeetCode--reverse-nodes-in-k-group
- Leetcode: Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- LeetCode题解: Reverse Nodes in k-Group
- 【leetcode 链表相关】Reverse Nodes in k-Group
- 【LeetCode】Swap Nodes in Pairs && Reverse Nodes in k-Group
- [Leetcode]Reverse Nodes in k-Group
- 47_leetcode_Reverse Nodes in k-Group
- [Leetcode]_25 Reverse Nodes in k-Group