博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Reverse Nodes in k-Group
阅读量:7116 次
发布时间:2019-06-28

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

题目描述:

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

  这道题难度级别为Hard,其实并不Hard。

solution:

ListNode* reverse(ListNode *head,ListNode *end){    ListNode *p = head;    ListNode *newHead = NULL;    while (p != end)    {        ListNode *tmp = p;        p = p->next;        tmp->next = newHead;        newHead = tmp;    }    return newHead;}ListNode* reverseKGroup(ListNode* head, int k) {    if(k <= 1)        return head;    int length = 0;    ListNode *p = head;    while (p != NULL && length != k)    {        ++length;        p = p->next;    }    if(length < k)        return head;    ListNode *newHead = reverse(head, p);    p = reverseKGroup(p, k);    head->next = p;    return newHead;}

 

转载于:https://www.cnblogs.com/gattaca/p/4499545.html

你可能感兴趣的文章
C#Css/Js静态文件压缩--Yui.Compressor.Net
查看>>
配置tomcat的https通信(单向认证)
查看>>
Intellij Idea @Autowired取消提示
查看>>
httpclient调用https
查看>>
Oracle数据库中有关记录个数的查询
查看>>
sql语句查询出表里符合条件的第二条记录的方法
查看>>
题目1008:最短路径问题
查看>>
PHPExcel正确读取excel表格时间单元格(转载)
查看>>
继电器是如何成为CPU的
查看>>
分布式缓存
查看>>
Android-ViewPager+Fragment数据更新问题
查看>>
[WASM] Compile C Code into WebAssembly
查看>>
JAVA8-让代码更优雅之List排序
查看>>
为什么我的淘宝排名会突然下降?
查看>>
SecureCRT常用快捷键
查看>>
java使用Rome解析Rss的实例(转)
查看>>
零基础 Vue 开发环境搭建 打开运行Vue项目
查看>>
tensorflow 笔记12:函数区别:placeholder,variable,get_variable,参数共享
查看>>
(转)漫谈MySql中的事务
查看>>
将逗号分隔的字符串与List互转
查看>>