[Linked List]Reverse Nodes in k-Group
2015-12-12 16:01
609 查看
Total Accepted: 48614 Total Submissions: 185356 Difficulty: Hard
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:
(M) Swap Nodes in Pairs
Next challenges: (M) Rotate List (M) Reorder List (M) Sort List
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
(M) Swap Nodes in Pairs
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* newHead=NULL,*p=head,*next=NULL; while(p){ next = p->next; p->next = newHead; newHead = p; p = next; } return newHead; } ListNode* reverseKGroup(ListNode* head, int k) { if(k<=1){ return head; } ListNode *pre=NULL,*next=NULL; ListNode *cur=head; ListNode *reverseHead = NULL; int cnt = 0; while(cur){ if(cnt==0){ reverseHead = cur; } next = cur->next; ++cnt; if(cnt==k){ cur->next=NULL; ListNode *newHead = reverseList(reverseHead); pre ? pre->next = newHead : head=newHead; reverseHead->next = next; pre = reverseHead; cur = next; cnt = 0; }else{ cur = cur->next; } } return head; } };
Next challenges: (M) Rotate List (M) Reorder List (M) Sort List
相关文章推荐
- LeetCode Swap Nodes in Pairs
- [Linked List]Swap Nodes in Pairs
- [Linked List]Delete Node in a Linked List
- nodejs基础
- Node.js的优点和缺点(转载)
- nodejs 配置及其nodejs管理工具npm
- nodejs初探(四)实现一个多人聊天室
- nodejs初探(三)实现一个简单的socket交互
- nodejs初探(二)第一个nodejs程序“hello world”
- nodejs初探(一)环境搭建,开发工具安装
- LeetCode 237 Delete Node in a Linked List
- [Linked List]Remove Nth Node From End of List
- node.js express开发web问题
- 10、osg::AnimationPath,osg::NodeVisitor类
- LeetCode 237:Delete Node in a Linked List
- leetcode Remove Nth Node From End of List
- node 学习笔记 - Modules 模块加载系统 (1)
- [转]为什么我要用 Node.js? 案例逐一介绍
- LeetCode:Remove Nth Node From End of List
- 安装nodejs时提示Leaving directory