File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Linked_List/092.Reverse-Linked-List-II Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * Definition for singly-linked list.
3+ * struct ListNode {
4+ * int val;
5+ * ListNode *next;
6+ * ListNode() : val(0), next(nullptr) {}
7+ * ListNode(int x) : val(x), next(nullptr) {}
8+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9+ * };
10+ */
11+ class Solution {
12+ public:
13+ ListNode* reverseBetween (ListNode* head, int left, int right)
14+ {
15+ ListNode* dummy = new ListNode (0 );
16+ dummy->next = head;
17+
18+ ListNode* p = dummy;
19+ for (int i=0 ; i<right; i++)
20+ p = p->next ;
21+ ListNode* c = p->next ;
22+ p->next = NULL ;
23+
24+ p = dummy;
25+ for (int i=0 ; i<left-1 ; i++)
26+ p = p->next ;
27+ ListNode* b = p->next ;
28+ p->next = NULL ;
29+
30+ b = reverseLinkedList (b);
31+
32+ p = dummy;
33+ while (p->next ) p = p->next ;
34+ p->next = b;
35+ while (p->next ) p = p->next ;
36+ p->next = c;
37+
38+ return dummy->next ;
39+ }
40+
41+ ListNode* reverseLinkedList (ListNode* h)
42+ {
43+ ListNode* last = NULL ;
44+ ListNode* cur = h;
45+ ListNode* nxt;
46+ while (cur)
47+ {
48+ nxt = cur->next ;
49+ cur->next = last;
50+ last = cur;
51+ cur = nxt;
52+ }
53+ return last;
54+ }
55+ };
You can’t perform that action at this time.
0 commit comments