Reverse Nodes in k-Group
来源:互联网 发布:安装包制作工具 知乎 编辑:程序博客网 时间:2024/04/26 04:20
Q:
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: 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:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (head == null || head.next == null || k == 1) return head; ListNode cur = head; int n = 0; while (cur != null) { cur = cur.next; n++; } int group = n / k; if (group == 0) return head; cur = head.next; ListNode prev = head; prev.next = null; ListNode newTail = null; ListNode lastTail = prev; for (int i = 1; i < k; i++) { // this should not happen if (cur == null) break; ListNode temp = cur.next; cur.next = prev; prev = cur; cur = temp; } ListNode retHead = prev; lastTail.next = cur; for (int i = 1; i < group; i++) { newTail = cur; prev = cur; cur = cur.next; prev.next = null; for (int j = 1; j < k; j++) { // this should not happen if (cur == null) break; ListNode temp = cur.next; cur.next = prev; prev = cur; cur = temp; } lastTail.next = prev; lastTail = newTail; } lastTail.next = cur; return retHead; }}
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
- 数字集成电路设计-15-DPI(续)
- 范冰冰着大仁哥新装出街 款款皆真爱
- mac/windows/linux中eclipse搭建Android开发环境,无法访问dl-ssl.google.com
- Android LayoutInflater
- mezzanine problem——01
- Reverse Nodes in k-Group
- mongodb学习3-主从配置
- 编译器之神vim大改造
- Cleaning Shifts - POJ 2376 贪心
- ASN-MIB
- PAT (Advanced Level) Practise 1016. Phone Bills (25)
- Centos系统备份与恢复教程
- win7下硬盘安装Ubuntu 14.04
- N!(杭电1042)(数组实现+java实现)