leetcode25~Reverse Nodes in k-Group
来源:互联网 发布:国外社交软件排名 编辑:程序博客网 时间:2024/04/28 00:21
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
采用了递归和非递归的解法,与上题类似,不过这是在K个节点进行翻转。具体解释在程序中。
public class ReverseNodeskGroup { //递归实现 public ListNode reverseKGroup(ListNode head, int k) { ListNode curr = head; int count = 0; while(curr!=null && count!=k) { curr = curr.next; count++; } //找到curr为k+1节点 if(count==k) { //以curr作为头节点 curr = reverseKGroup(curr, k); while(count-- >0) { ListNode tmp = head.next; head.next = curr; curr = head; head = tmp; } //curr此时为翻转后的第一个节点 head = curr; } return head; } //非递归实现 public ListNode reverseKGroup2(ListNode head, int k) { if(head==null || k==1) return head; ListNode dummyNode = new ListNode(-1); dummyNode.next = head; ListNode pre = dummyNode; ListNode cur = head; int count = 0; while(cur!=null) { count++; //保存下一组的第一个节点 ListNode next = cur.next; if(count==k) { //将变换之后的最后一个节点也就是变换之前的第一个节点赋值给pre pre = reverse(pre,next); count=0; } //这里cur.next已经发生变化了,不能cur = cur.next cur = next; } return dummyNode.next; } private ListNode reverse(ListNode pre, ListNode next) { //需要改变pre指针,使之最后指向该组的最后一个节点 //最后返回的是last指针,该组的第一个节点 ListNode last = pre.next; ListNode curr = last.next; while(curr!=next) { last.next = curr.next; curr.next = pre.next; pre.next = curr; curr = last.next; } return last; }}
0 0
- [LeetCode25]Reverse Nodes in k-Group
- Leetcode25 Reverse Nodes in k-Group
- leetcode25 Reverse Nodes in k-Group
- leetcode25---Reverse Nodes in k-Group
- LeetCode25. Reverse Nodes in k-Group
- leetcode25: Reverse Nodes in k-Group
- leetcode25~Reverse Nodes in k-Group
- leetcode25. Reverse Nodes in k-Group
- LeetCode25. Reverse Nodes in k-Group
- leetcode25. 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
- STL标准模版库---set操作
- log4j.properties配置与加载应用
- JS验证表单集合大全
- Oracle中用exp/imp命令参数详解
- codevs1226 倒水问题 bfs
- leetcode25~Reverse Nodes in k-Group
- JMeter学习(一)工具简单介绍
- 浏览器的一个请求从发送到返回都经历了什么,讲的越详细越好
- 旋转打印矩阵
- JavaScript函数集合大全
- 89. Gray Code
- 94. Binary Tree Inorder Traversal
- 深入剖析Tomcat 第四章 默认连接器
- GUID与CString转换函数