Reverse Linked List II
2014-05-02 00:23
190 查看
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-1,m,n,n+1,只要把这四个点弄明白后,然后改变m到n间的指针方向,就OK了。首先找出m-1的点,然后找出m点,经循环后得到n和n+1的点。
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-1,m,n,n+1,只要把这四个点弄明白后,然后改变m到n间的指针方向,就OK了。首先找出m-1的点,然后找出m点,经循环后得到n和n+1的点。
/** * 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) { if(head==NULL) return NULL; ListNode *pPre=NULL;//找出m-1点的位置 ListNode *pList=head; for(int i=1;i<m;i++) { pPre=pList; pList=pList->next; } ListNode *pLeft=pList; //m点位置 ListNode *pRight=pList;//找出n点的位置 ListNode *pTail;//找出n+1点的位置 for(int i=m;i<=n;i++) { pTail=pList->next; pList->next=pRight; pRight=pList; pList=pTail; } if(pPre==NULL) { head=pRight; } else { pPre->next=pRight; } pLeft->next=pTail; return head; } };
相关文章推荐
- Pig安装及本地模式实战
- 探究 C++ Singleton(单例模式)
- 【DFS】DLUToj-1215-组合数字
- JAVA中获取当前系统时间
- HDU 4407
- 一种简单实用的全屏方法
- 黑马程序员-Oracle(第三讲)
- 时间值
- php2014-4-31的总结
- 初识libjpeg
- Android下生成pdf并显示中文
- 在VC资源文件中加入声音资源
- C++ primer读书笔记(1)
- ios 动画中如何正确响应button的各种事件
- VC++实现位图显示透明效果--实现原理
- 事务管理(二) JDBC事务管理简单实现
- 练习写C++代码(11)--实现简单的时钟类3
- [Redis]windows下redis安装
- linux下源码搭建php环境之mysql(一)
- google glog分析2