博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode开心刷题十四天——25Reverse Nodes in k-Group
阅读量:4557 次
发布时间:2019-06-08

本文共 2176 字,大约阅读时间需要 7 分钟。

25. Reverse Nodes in k-Group
Hard
1222257FavoriteShare

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed

改进声明:

本方法速度和内存好像都比较差,虽然思路简洁,但是可能构造技巧上还是有进步空间

main idea:

One word to sum up the idea,victory! haaa~just a joke

Group

In this reverse problem,group is important,devide into ordered &inordered.three pointers we need to correctly understanding the meaning of these variables.cur->ordered part end ,nxt->inordered start,pre->before these parts.

It looks like this composition:

pre->order part->inorder part->left_out

Now it's the code

 

#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { //this situation can include head->next //special case dispose if(!head||k==1) return head; //dummy node ListNode dummy(0); dummy.next=head; //len calc int len=1; while(head=head->next) len++; //cout<
<
next; ListNode *nxt=cur->next; for(int j=1;j
next=nxt->next; nxt->next=pre->next; pre->next=nxt; nxt=cur->next; } pre=cur; } return dummy.next; }};int main(){ int k; cin>>k; ListNode a(1); ListNode b(2); ListNode c(3); ListNode d(4); ListNode e(5); Solution s; a.next=&b; b.next=&c; c.next=&d; d.next=&e; ListNode *head=&a;// while(head)// {// cout<
val<
next;// } ListNode* res=NULL; res=s.reverseKGroup(head, k); while(res) { cout<
val<
next; } return 0;}

 

 

转载于:https://www.cnblogs.com/Marigolci/p/11145448.html

你可能感兴趣的文章
Uva10290 - {Sum+=i++} to Reach N
查看>>
每日一小练——数值自乘递归解
查看>>
二叉搜索树 (BST) 的创建以及遍历
查看>>
MyBatis/Ibatis中#和$的区别
查看>>
【JAVASCRIPT】React学习-组件生命周期
查看>>
win 64 文件操作
查看>>
LeetCode : First Bad Version
查看>>
pythone函数基础(14)发送邮件
查看>>
Java的一些好看的
查看>>
Linux 修改文件夹和其中所有文件的权限
查看>>
详解volatile 关键字与内存可见性
查看>>
go 聊天室简单版总结
查看>>
HDU 4258 斜率优化dp
查看>>
Literature review
查看>>
Java 中可变参数
查看>>
PyTorch在64位Windows下的Conda包(转载)
查看>>
php的单元测试,PHPUnit安装
查看>>
CentOS7 设置软件镜像源
查看>>
Java并发编程:并发容器之ConcurrentHashMap
查看>>
Java范例集锦(二)
查看>>