leetcode 反转链表部分节点
2024-09-16 08:20:36
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
/*
* @lc app=leetcode.cn id=92 lang=cpp
*
* [92] 反转链表 II
*/ // @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void printList(ListNode* head) {
ListNode* cur = head;
printf("list: %d ", cur->val);
while(cur->next != NULL) {
cur = cur->next;
printf("%d ", cur->val);
}
printf("\n");
}
ListNode* reverse(ListNode* head, int count) {
// printList(head); ListNode* cur = head;
ListNode* curNew = NULL;
ListNode** ptr = &curNew; int times = ;
while(cur) {
ListNode* tmp = cur->next;
cur->next = curNew;
curNew = cur;
cur = tmp; times++;
if(times > count) { //找到反转链表结束位置
// printf("cur %d\n", cur->val);
head->next = cur;
break;
}
}
// printList(curNew);
return curNew;
} ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* cur = head;
ListNode* curNew = NULL; if (m > ) {
// 找到m-1位置的节点
for(int i = ; i< m; i++) {
curNew = cur;
cur = cur->next;
}
// m-1 的节点的next指向反转链表
curNew->next = reverse(cur, n - m);
return head;
} else {
return reverse(cur, n - m);
}
}
};
// @lc code=end
最新文章
- 第二天--html
- Lucene中几种常用的Query
- iOS开发MAC下配置Svn和Git
- 在IE8中使用padding设置select控件文字垂直居中
- Python全栈--9 __import__ 反射和面向对象基础 self 封装 继承(多继承的顺序) 多态
- 第二周02:Fusion ICP逐帧融合
- HTML5 微信二维码提示框
- 自定义Back返回键(实现按两次返回键退出程序)
- 在SPItemEventReceiver中使用BeforeProperties和AfterProperties
- 驱动: i2c驱动 >;>;>;>;
- vector,list,deque
- html5之img标签
- android 自定义下拉菜单
- hdu 5536 Chip Factory (01 Trie)
- 关于动态添加iview admin路由以及刷新侧边栏
- JavaWeb网上商城项目中sql语句问题的解决
- Windows结构化异常处理浅析
- PHP单例模式实例,连接数据库对类的引用
- 【Spring源码分析系列】启动component-scan类扫描加载过程
- Object-C-Foundation-NSNuber
热门文章
- 8.1Go并发
- MYSQL LOCK IN SHARE MODE&;FOR UPDATE
- apache.zookeeper-3.4与apache.kafka-2.11的安装
- Oracle操作时间-----摘抄而来
- xampp apache 安全性问题
- hdu3861他的子问题是poj2762二分匹配+Tarjan+有向图拆点 其实就是求DAG的最小覆盖点
- Shone.Math开源系列1 — 基于.NET 5实现Math<;T>;泛型数值计算
- WEB常见攻击及防御
- springmvc拦截器和概念,配置!!!
- vue中 transition组件使用总结