-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseLinkedListII.h
48 lines (39 loc) · 1.18 KB
/
ReverseLinkedListII.h
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Author: naiyong, aonaiyong@gmail.com
Date: Sep 22, 2014
Problem: Reverse Linked List II
Difficulty: 3
Source: https://oj.leetcode.com/problems/reverse-linked-list-ii/
Notes:
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.
Solution: Two pointers.
*/
#ifndef REVERSELINKEDLISTII_H_
#define REVERSELINKEDLISTII_H_
#include "ListNode.h"
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
ListNode dummy(0), *prev = &dummy;
dummy.next = head;
// traverse to position m - 1
for (int i = 0; i < m - 1; ++i)
prev = prev->next;
// reverse nodes from position m + 1 to n
ListNode *first = prev->next;
for (int i = 0; i < n - m; ++i) {
ListNode *second = first->next;
first->next = second->next;
second->next = prev->next;
prev->next = second;
}
return dummy.next;
}
};
#endif /* REVERSELINKEDLISTII_H_ */