# Reverse Linked List II

Problem:

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 ≤ m ≤ n ≤ length of list.

 1 if(head == NULL)
2     return;
3
4 ListNode *tail = head;
5 while(tail->next) {
6     ListNode *cur = tail->next;
7     tail->next = cur->next;
8     cur->next = head;
9     head = cur;
10 }

 1 class Solution {
2 public:
3     ListNode *reverseBetween(ListNode *head, int m, int n) {
4         if(head == NULL || m == n || m < 1 || m > n)
6
7         ListNode *sentinel = new ListNode(0);
8         sentinel->next = head;
9         ListNode *pre = sentinel;
10         for(int i = 1; i < m; ++i) {
11             pre = pre->next;
12         }
13         ListNode *tail = pre->next;
14         for(int i = m; i < n; ++i) {
15             ListNode *cur = tail->next;
16             tail->next = cur->next;
17             cur->next = pre->next;
18             pre->next = cur;
19         }
20         head = sentinel->next;
21         delete sentinel;
23     }
24 };

posted @ 2014-04-30 20:49  夏目家的猫咪老师  阅读(255)  评论(0编辑  收藏  举报