25.Reverse Nodes in k-Group
2016-03-15 23:42
609 查看
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
Subscribe to see which companies
asked this question
思路:递归。首先找到第k+1个节点,也就是这一段需要翻转的链表的尾部相连的那个节点。如果找不到第k+1个节点,说明这一段链表长度不足k,无需进行翻转。在找到第k+1个节点的情况下,首先递归求后面直接相连的链表翻转之后的的头结点。然后再将这个头结点之前的需要翻转的链表节点逐个重新连接,进行翻转。最终,返回翻转之后的链表的头结点。
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
Subscribe to see which companies
asked this question
思路:递归。首先找到第k+1个节点,也就是这一段需要翻转的链表的尾部相连的那个节点。如果找不到第k+1个节点,说明这一段链表长度不足k,无需进行翻转。在找到第k+1个节点的情况下,首先递归求后面直接相连的链表翻转之后的的头结点。然后再将这个头结点之前的需要翻转的链表节点逐个重新连接,进行翻转。最终,返回翻转之后的链表的头结点。
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *cur=head; int count=0; //找到第k+1个节点 while(cur&&count!=k){ cur=cur->next; count++; } //找到了第k+1个节点,开始进行翻转 if(count==k){ //下一段链表翻转之后的头结点 cur =reverseKGroup(cur,k); while(count-->0){ ListNode *temp =head->next; head->next=cur;//将head指向cur cur=head;//将cur向前移动一位 head=temp;//将head向后移动一位 } head=cur;//此时,头结点变成原来的尾部节点 } return head;//返回head } };
相关文章推荐
- Node.js入门
- hadoop集群启动后,datanode节点上jps后NodeManager无法启动
- node.js用get方式获取网页中的链接
- node.js实现多图片上传
- PostgresXC:从源码编译、安装、配置数据库集群以及用pg_basebackup配置Datanode的热备份
- nodejs 大致学习二 普通的脚本 类似python
- nodejs大致学习
- Nodejs学习笔记(四)与MySQL交互(felixge/node-mysql)
- A1115. Counting Nodes in a BST (30)
- VS轻松开发Node.js应用
- nodejs一些比较实用的命令
- Nodejs Q promise设计思路
- Nodejs "=="与“===”的区别
- 19. Remove Nth Node From End of List
- nodejs中package.json文件模块依赖的版本格式
- Node.js的线程和进程*2014年4月的文章
- Node.js简介和安装
- lintcode: Insert Node in a Binary Search Tree
- LightOJ1094 - Farthest Nodes in a Tree(树的直径)
- GDataXMLNode应用