leetCode(11):Reverse linked list II
2015-06-18 15:16
246 查看
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
4,
return
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
最麻烦的还是从头结点开始转化,考虑问题要全面。
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.
最麻烦的还是从头结点开始转化,考虑问题要全面。
/** * 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) { int i=1; if(head==NULL) return NULL; if(head->next==NULL) return head; if(m==n) return head; ListNode* p=head; ListNode* pM=NULL; ListNode* p1=NULL; ListNode* p2=NULL; ListNode* p3=NULL; ListNode* tail=NULL; if(m==1) { p1=head; tail=p1; p2=p1->next; p3=p2->next; if(p3==NULL) { head=p2; p2->next=p1; p1->next=NULL; return head; } } while(i<n-1) { if(i+1==m) { pM=p;//反转起点上一结点 tail=pM->next; p1=pM->next;//反转起点 p2=p1->next; p3=p2->next; } if(i>=m-1) { p2->next=p1; p1=p2; p2=p3; if(p3) p3=p3->next; } else p=p->next; i++; } if(m==1) { p2->next=p1; tail->next=p3; return p2; } if(n==2) { p2->next=p1; p1->next=p3; return p2; } pM->next=p1; tail->next=p2; return head; } };
相关文章推荐
- 获取屏幕高度、宽度
- leetCode(11):Reverse linked list II 分类: leetCode 2015-06-18 15:16 154人阅读 评论(0) 收藏
- nginx 设置反响代理实现nginx集群
- mongo api
- gcc中关于静态库和动态库使用
- Android 访问网络连接设置界面
- Win8/8.1快速关闭右边桌面超级菜单的方法
- linux进程高cpu问题分析
- Webcontent路径结果显示
- Android 简易计算器程序
- iOS 多语言支持
- DOS net 命令
- TripWire公司威胁情报产品做了什么
- 织梦DEDECMS网站安全攻略之修改data目录名称方法步骤
- Uva - 506 - System Dependencies
- MFC 启用和禁用控件
- Uva - 506 - System Dependencies
- ABAP动态生成经典应用之Dynamic SQL Excute 程序
- php 待整理
- Mybatis实现对数据(oracle数据库)的增删改查(crud)