问题描述

给定一个链表,要求翻转其中从m到n位上的节点,返回新的头结点。

Example

Input: 1->2->3->4->5->NULL, m = 2, n = 4

Output: 1->4->3->2->5->NULL

分析

这题解法比较直接,可以定义一个fakeNode, 首先拼接 1 到 m - 1的节点, 然后拼接链表 m 到 n reverse 之后的结果,最后拼接剩下的节点。reverse链表这里主要使用stack和3指针方法。

解法

方法1. Stack

 ListNode fakeHead = new ListNode(0);
ListNode cur =fakeHead;
ListNode curH = head;
int cnt = n - m + 1;
//链接 1到m - 1节点
while(m > 1){
cur.next = curH;
curH = curH.next;
cur = cur.next;
m--;
}
cur.next = null;
//链接m 到 n 翻转之后的结果
Stack<ListNode> stack =new Stack();
for(int i = 0; i < cnt; i++){
stack.push(curH);
curH = curH.next;
}
while(!stack.isEmpty()){
cur.next = stack.pop();
cur = cur.next;
}
//链接 n + 1 之后的链表
cur.next = curH; return fakeHead.next;

时间复杂度O(n),空间复杂度O(n)

方法2. 3指针

 public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode fakeHead = new ListNode(0);
ListNode cur =fakeHead;
ListNode curH = head;
int cnt = n - m + 1;
//链接 1到m - 1节点
while(m > 1){
cur.next = curH;
curH = curH.next;
cur = cur.next;
m--;
}
cur.next = null;
//链接m 到 n 翻转之后的结果
ListNode pre = null;
ListNode next = curH.next;
ListNode tail =curH;
for(int i = 0; i < cnt; i++){
curH.next = pre;
pre = curH;
curH = next;
if(next != null){
next = next.next;
}
}
cur.next = pre;
//链接 n + 1 之后的链表
tail.next = curH; return fakeHead.next;
}

时间复杂度O(n),空间复杂度O(1)

最新文章

  1. SharePoint2016合规性策略中心
  2. Dev GridView行拖拽
  3. 商贸食品车销成功应用PDA抄单 现场开单 打印销售单安卓智能手持POS应用
  4. c++ c# java 调用 c++ 写的dll
  5. nunjucks.js模板渲染
  6. Spring boot中使用springfox来生成Swagger Specification小结
  7. Hibernate配置文件和映射元素解释
  8. jvm常量池 vsv为什么1000 == 1000返回为False,而100 == 100会返回为True?
  9. Servlet+Tomcat 界面登录
  10. Android的logcat命令详解
  11. 七牛用户如何将视频转码成普清高清来适应不同的手机端或者web端
  12. commondatastorage.googleapis.com訪问失败高速解决
  13. .NET并行与多线程学习系列一
  14. 《android入门第一季》之android目录结构详解
  15. c语言五子棋
  16. LeetCode 905. Sort Array By Parity
  17. 贝叶斯---最大似然估计(高翔slam---第六讲 )
  18. android样式之按钮&amp;&amp;图片
  19. html的初了解(更新中&#183;&#183;&#183;)
  20. 安装unity3d多个版本共存

热门文章

  1. Incorrect string value: &#39;\xF0\x9F\x92\x8BTi...&#39;错误
  2. 【JavaEE】之MyBatis开发DAO
  3. if判断语句的总结
  4. java程序员面试答题技巧
  5. HTTPS工作流程(入门)
  6. Java数组与C/C++数组的区别
  7. 个性的圆角.html
  8. 从自动化到智能化,网易杭研的AIOps探索与实践
  9. springboot-整合多数据源配置
  10. MongoDB第三天(正则,管道,聚合,字符串,算术,日期,java连接MongoDB)