码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Linked List II

时间:2014-10-28 11:41:46      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   for   sp   div   on   

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         if (head == NULL || m > n) return NULL;
13         ListNode* pmprev = NULL;// 始终指向第m个节点的前缀
14         ListNode* pn = NULL; //指向逆置后的第n个节点
15         ListNode* pm = NULL; //指向第m个节点
16         ListNode *pter = NULL; //操作节点
17         ListNode *pter_next = NULL; //指向操作节点的下一个节点
18         pter = head;
19         
20         for (int i = 1; i < m; ++i) {
21             pmprev = pter;
22             pter = pter->next;
23         }
24         
25         pn = pm = pter;
26         for (int i = m; i <= n; ++i) {
27             pter_next = pter->next;
28             pter->next = pn;
29             pn = pter;
30             pter = pter_next;
31         }
32         
33         if (pmprev == NULL) { //如果头结点也在逆置范围中
34             head = pn;
35         } else {
36             pmprev->next = pn;
37         }
38         
39         pm->next = pter_next;
40         
41         return head;
42     }
43 };

 

[LeetCode] Reverse Linked List II

标签:style   blog   io   color   os   for   sp   div   on   

原文地址:http://www.cnblogs.com/vincently/p/4056291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!