-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_206_ReverseLinkedListII.cpp
80 lines (69 loc) · 2.09 KB
/
LC_206_ReverseLinkedListII.cpp
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
https://leetcode.com/problems/reverse-linked-list-ii/
92. Reverse Linked List II
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
/*
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummyHead = new ListNode(0, head);
ListNode* ptr = head, *prevptr = dummyHead;
int cnt = 1;
while(cnt!=left)
{
cnt++;
prevptr = ptr;
ptr=ptr->next;
}
// cout<<prevptr->val<<"<-prevptr "<<endl;
// cout<<ptr->val<<"<-ptrval "<<endl;
// cout<<cnt<<"<-cnt "<<endl;
//Three Pointer Approach
ListNode* prev = nullptr ;
ListNode* curr = ptr ;
ListNode* newp = nullptr ;
cnt--;
while(cnt!=right)
{
cnt++;
newp = curr->next;
curr->next = prev;
prev = curr;
curr = newp;
}
// cout<<newp->val<<"<-newp "<<endl;
// cout<<prev->val<<"<-prev "<<endl;
// cout<<cnt<<"<-cnt "<<endl;
prevptr->next = prev; //non-reverse-LL to new head of reverse LL
ptr->next = newp; // old head of reverse LL to non-reverse right part
return dummyHead->next;
}
*/
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode dummyHead = ListNode(-1, head);
ListNode *prev = &dummyHead;
ListNode *cur = head, * pnxt = nullptr, * cnxt = nullptr;
for(int i=0; i<left-1; i++)
prev = prev->next;
cur = prev->next;
for(int i=0; i<right-left; i++)
{
pnxt = prev->next;
cnxt = cur->next;
prev->next = cnxt;
cur->next = cnxt->next;
cnxt->next = pnxt;
}
return dummyHead.next;
}
};