Leetcode92: Reverse Linked List II 翻转链表问题
2024-09-01 21:20:08
问题描述
给定一个链表,要求翻转其中从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)
最新文章
- SharePoint2016合规性策略中心
- Dev GridView行拖拽
- 商贸食品车销成功应用PDA抄单 现场开单 打印销售单安卓智能手持POS应用
- c++ c# java 调用 c++ 写的dll
- nunjucks.js模板渲染
- Spring boot中使用springfox来生成Swagger Specification小结
- Hibernate配置文件和映射元素解释
- jvm常量池 vsv为什么1000 == 1000返回为False,而100 == 100会返回为True?
- Servlet+Tomcat 界面登录
- Android的logcat命令详解
- 七牛用户如何将视频转码成普清高清来适应不同的手机端或者web端
- commondatastorage.googleapis.com訪问失败高速解决
- .NET并行与多线程学习系列一
- 《android入门第一季》之android目录结构详解
- c语言五子棋
- LeetCode 905. Sort Array By Parity
- 贝叶斯---最大似然估计(高翔slam---第六讲 )
- android样式之按钮&;&;图片
- html的初了解(更新中&#183;&#183;&#183;)
- 安装unity3d多个版本共存
热门文章
- Incorrect string value: &#39;\xF0\x9F\x92\x8BTi...&#39;错误
- 【JavaEE】之MyBatis开发DAO
- if判断语句的总结
- java程序员面试答题技巧
- HTTPS工作流程(入门)
- Java数组与C/C++数组的区别
- 个性的圆角.html
- 从自动化到智能化,网易杭研的AIOps探索与实践
- springboot-整合多数据源配置
- MongoDB第三天(正则,管道,聚合,字符串,算术,日期,java连接MongoDB)