Skip to content

Commit

Permalink
LeetCode: 92. Reverse Linked List II;
Browse files Browse the repository at this point in the history
- accepted;
  • Loading branch information
olegon committed Jul 28, 2023
1 parent 724e48b commit b083732
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
5 changes: 5 additions & 0 deletions leetcode/problems/reverse-linked-list-ii/compile-and-run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

set -x

clang++ main.cpp -W -Wall -std=c++17 -O2 -fsanitize=address && ./a.out
90 changes: 90 additions & 0 deletions leetcode/problems/reverse-linked-list-ii/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
92. Reverse Linked List II
https://leetcode.com/problems/reverse-linked-list-ii
*/

#include <bits/stdc++.h>

using namespace std;


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 *current = head;
ListNode *previous = nullptr;

while (left > 1) {
previous = current;
current = current->next;

left--;
right--;
}

cout << current->val << endl;

ListNode *currentBeforeInverting = current;
ListNode *previousBeforeInverting = previous;

while (right-- > 0) {
ListNode *next = current->next;

current->next = previous;
previous = current;
current = next;
}

currentBeforeInverting->next = current;

if (previousBeforeInverting == nullptr) {
head = previous;
}
else {
previousBeforeInverting->next = previous;
}

return head;
}
};

class RecursiveSolution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (left > 1) {
head->next = reverseBetween(head->next, left - 1, right - 1);
}
else {
ListNode* curr = head;
ListNode* prev = nullptr;

while (right-- > 0) {
ListNode *next = curr->next;

curr->next = prev;
prev = curr;
curr = next;
}

head->next = curr;

return prev;
}

return head;
}
};

int main(void) {
ios::sync_with_stdio(false);

return EXIT_SUCCESS;
}

0 comments on commit b083732

Please sign in to comment.