aboutsummaryrefslogtreecommitdiff
path: root/reverse_linked_list2.cpp
blob: dbbb261202c03e1ad6e3d2759c7fa8adf8245900 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "leetcode.h"

class Solution {
public:
  ListNode *reverseBetween(ListNode *head, int left, int right) {
    if (head == NULL || head->next == NULL)
      return head;
    ListNode *tmp = new ListNode(-1);
    tmp->next = head;
    ListNode *itL = tmp, *preL = NULL;
    for (int i = 0; i < left; i++) {
      preL = itL;
      itL = itL->next;
    }
    ListNode *itR = itL, *preR = preL;
    for (int i = left; i <= right; i++) {
      ListNode *forward = itR->next;
      itR->next = preR;
      preR = itR;
      itR = forward;
    }
    preL->next = preR;
    itL->next = itR;
    return tmp->next;
  }
};