92. Reverse Linked List II
2015-08-06 16:29
281 查看
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
return
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
分析:找到m节点,从节点m到n依次反转指针,然后把翻转后的串连起来即可。注意在反转指针的时候,需要三个指针,分别为pre、p和pafter。
For example:
Given
1->2->3->4->5->NULL, m = 2 and n = 4,
return
1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
分析:找到m节点,从节点m到n依次反转指针,然后把翻转后的串连起来即可。注意在反转指针的时候,需要三个指针,分别为pre、p和pafter。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == NULL)return NULL; //为了操作方便,添加额外的头结点tmpHead ListNode *tmpHead = new ListNode(0), *p = head, *mpre = tmpHead; tmpHead->next = head; for(int i = 1; i < m; i++) {mpre = p; p = p->next;}//找到m节点 ListNode *pafter = p->next, *mbackup = p; for(int i = 1; i <= n-m; i++) {//反转m到n的指针 ListNode *pre = p; p = pafter; pafter = pafter->next; p->next = pre; } //连接 mbackup->next = pafter; mpre->next = p; head = tmpHead->next; delete tmpHead; return head; } };
相关文章推荐
- Openjudge1487 Highways(prim)
- 表值参数学习
- javascript 变量 命名规范 变量的作用域
- Android应用安全之第三方SDK安全
- Android-Universal-Image-Loader的使用注意事项
- 四款PDF文档制作软件横向评测
- SpringMVC学习系列(11) 之 表单标签
- Ajax返回数据类型
- Eclipse里Tomcat启动贼慢的解决方法
- LCA算法
- 开心消消乐
- 测试城市电话号码
- Python 时间格式化
- java使用Redis3--完整模板类
- 【暑假】[实用数据结构]动态连续和查询问题
- 如何保存网页
- js获取GET数据
- Cocos2d-x 3.6 项目实战---贪吃蛇(2)
- Hosts文件的作用
- js获取当前时间