LeetCode 25: Reverse Nodes in k-Group
2015-06-08 20:00
567 查看
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:
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个一组,反序后,形成新的链表。对于最后不满K个元素,保持原来的顺序输出。所以本题可以按如下方法解:
1、建立空的新链表list1.
2、如果原链表剩余元素个数不小于K个,则取K个元素,采用头插法构建反序的临时链表,插入list1的尾部。
3、如果链表剩余元素个数小于K个,则将剩余的链表插入到list1的尾部。
代码如下:
//计算链表长度 int getListSize(ListNode* head) { int count = 0; while (head) { head = head->next; count++; } return count; } //在链表头部插入元素,返回插入后的链表头指针 ListNode* addHead(ListNode*head, ListNode*Node) { Node->next = head; return Node; } ListNode* reverseKGroup(ListNode* head, int k) { int length = getListSize(head); ListNode tmpHead(-1); ListNode *pNode = &tmpHead; while(length >= k){ ListNode* pHead = NULL; for (int i=0; i<k; i++) { ListNode*ptmpNode = head; head = head->next; ptmpNode->next = NULL; //透过头插法构建反序的临时链表 pHead = addHead(pHead, ptmpNode); } pNode->next = pHead; while(pNode->next) pNode = pNode->next; length -= k; } //将链表剩余元素插入结果链表的尾部 pNode->next = head; return tmpHead.next; }
相关文章推荐
- [LeetCode] Count Complete Tree Nodes
- 升级 node 版本
- 谁才是性能之王?( Node.js vs io.js v2.0.0 )
- LeetCode_24---Swap Nodes in Pairs
- 用链表实现nodejs的内存对象管理
- Node.js是一个事件驱动I/O服务端JavaScript环境
- puppet学习笔记之node/package/service/file/user/group/cron/exec管理
- IIS部署Nodejs步骤
- Hadoop中namenode/datanone没有启动
- nodejs - 如何完全更新
- leetcode 日经贴,Cpp code -Count Complete Tree Nodes
- Hadoop集群中启动namenode失败的解决办法
- leetcode 24 -- Swap Nodes in Pairs
- root.sh Fails on the First Node for 11gR2 Grid Infrastructure Installation
- node.js学习总结(不定期更新)
- nodejs express 框架使用
- Hadoop集群安全性:Hadoop中Namenode单点故障的解决方案及详介AvatarNode
- Populating Next Right Pointers in Each Node I, II
- npm and node 的一些问题
- [leetcode][tree] Count Complete Tree Nodes