Boostable

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

LeetCode: Reverse Linked List

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->NULL, m = 2 and n = 4,

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

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

地址:https://oj.leetcode.com/problems/reverse-linked-list-ii/

算法:先找到第m个节点p以及其前趋pre,然后把p记下,因为p是逆置链表部分的最后一个节点。然后从p开始遍历到第n个节点,并把节点依次插入pre后面,注意处理pre为空,也就是m=1的情况。代码:

 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)   return NULL;
13         ListNode *pre = NULL;
14         ListNode *p = head;
15         int i = 1;
16         while(p && i != m){
17             pre = p;
18             p = p->next;
19             ++i;
20         }
21         if(!p)  return head;
22         ListNode *first_reverse_node = p;
23         if(pre){
24             pre->next = NULL;
25         }
26         ListNode *q = p;
27         while(q && i <= n){
28             q = p->next;
29             if(pre){
30                 p->next = pre->next;
31                 pre->next = p;
32             }else{
33                 if(p == head)
34                     head->next = NULL;
35                 else{
36                     p->next = head;
37                     head = p;
38                 }
39             }
40             p = q;
41             ++i;
42         }
43         first_reverse_node->next = q;
44         return head;
45     }
46 };

 

posted on 2014-08-31 22:11  Boostable  阅读(314)  评论(0编辑  收藏  举报