Reverse Nodes in k-Group
来源:互联网 发布:南大女生碎尸案 知乎 编辑:程序博客网 时间:2024/04/30 10:04
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
0 -> 1 -> 2 -> 3 -> 4 - > 5
pre first end(cur) nextfirst
1、确定上述指针的位置;
2、反转first 到end之间的链表;
3、然后再把pre.next指向end,first.next指向nextfirst,然后移动四个指针的位置。
public ListNode reverseKGroup(ListNode head, int k) { if(head == null || k == 0 || k == 1) return head; ListNode newhead = new ListNode(0); newhead.next = head; ListNode pre = newhead; ListNode cur = head; ListNode first = head; while(cur != null){ for(int i = 1; i < k && cur != null; i ++){ cur = cur.next; } if(cur == null) break; ListNode nextfirst = cur.next; ListNode tmp = first; ListNode afttmp = tmp.next; tmp.next = null; while(tmp != cur){ ListNode next = afttmp.next; afttmp.next = tmp; tmp = afttmp; afttmp = next; } pre.next = cur; first.next = nextfirst; pre = first; first = nextfirst; cur = nextfirst; } return newhead.next; }
1 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
- 处理类型
- Swift - Alamofire - GET/POST/upload 的使用
- 《acm课程设计》总结
- 记一次Error:Execution failed for task ':o2osdk:transformClassesAndResourcesWithProguardForRelease'编译出错
- Python中yield的用法
- Reverse Nodes in k-Group
- 1747. 内存使用
- CodeForces 687B Remainders Game
- OpenCV2:Mat属性type,depth,step
- 如何判断栈、堆的增长方向?
- HDU 2602 Bone Collector
- 动态规划 解决打印所有和为s的连续整数序列 剑指offer 之 面试题41_2
- 第3章 主机规划与磁盘分区
- ContentType设置的内容