LeetCode 25 Reverse Nodes in k-Group
2016-06-08 00:00
260 查看
Reverse Nodes in k-Group
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:
代码如下:
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解题思路:题目要求里面很明显的规定了不准使用黑科技,即修改节点的值,所以这道题是一道实实在在的利用指针操作解决的。我的思路是先求出需要交换的pair的数目,然后从尾部开始遍历。为什么从尾部呢?因为如果从头部开始交换,会导致后面节点交换后,前面的节点丢失指针。当然,要注意pair接近末尾节点的时候要考虑边界问题。
代码如下:
public ListNode reverseKGroup(ListNode head, int k) { if(head==null||k==1){ return head; } ListNode l0 = head; int len =0; while(l0!=null){ len++; l0=l0.next; } if(k>len){ k=len; return head; } ListNode ls[] = new ListNode[len+1]; ListNode l1 = head; int index =0; int n = (len-len%k)/k; while(index<len){//记录所有指针 ls[index] = l1; l1 = l1.next; index++; } ListNode l2 = ls[k-1];//0-k for (int i = n; i >= 1; i--) {//从尾部开始做到头部 int g =i*k-1; int d = k*(i-1); while(g>=d){ if(g==d){ if((i+1)*k-1<len){ ls[g].next = ls[(i+1)*k-1]; }else{ ls[g].next = ls[i*k]; } }else{ ls[g].next = ls[g-1]; } g--; } } return l2; }
相关文章推荐
- LeetCode 24 Swap Nodes in Pair
- LeetCode 19 Remove Nth Node From End of List
- Windows系统下node.js的安装与配置
- [nodemon] Internal watch failed: watch ENOSPC错误解决办法
- node.js入门
- Node.js 框架比较: Express vs. Koa vs. Hapi
- 【Leetcode】Delete Node in a Linked List
- Sublime text 2/3 中 jade语法高亮
- nodejs MODEL层 封装(二)
- nodejs2
- windows 10 安装 hexo 续
- ActiveMQ + NodeJS + Stomp 入门
- node 获取本地IP地址
- 创建 Web 前端开发环境(node和npm)
- Populating Next Right Pointers in Each Node II
- window下安装node.js
- 如何在 Windows 10 中搭建 Node.js 环境?
- 如何在 Windows 10 中搭建 Node.js 环境?
- Populating Next Right Pointers in Each Node
- Delete Node in a Linked List