Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 14, 2020 19:27
Show Gist options
  • Save misterpoloy/f688a4710be34572d4c76e331395558f to your computer and use it in GitHub Desktop.
Save misterpoloy/f688a4710be34572d4c76e331395558f to your computer and use it in GitHub Desktop.
Reverse a Linked List using Stack
#include <iostream>
#include <stack>
struct Node {
int value;
Node* next;
Node(int value)
:next(nullptr), value(value)
{
}
};
class LinkedList {
public:
Node* head;
Node* tail;
LinkedList()
: head(nullptr), tail(nullptr)
{
}
void push(int value) {
Node* temporal = new Node(value);
if (tail == nullptr) {
head = temporal;
tail = temporal;
return;
}
tail->next = temporal;
tail = temporal;
}
void reverseUsingStack() {
std::stack<struct Node*> list;
Node* temporal = head;
while (temporal != nullptr) {
list.push(temporal);
temporal = temporal->next;
}
temporal = list.top();
head = temporal;
list.pop();
while (!list.empty()) {
temporal->next = list.top();
list.pop();
temporal = temporal->next;
}
// IMPORTANT! Don't forget
temporal->next = nullptr;
}
void print() {
Node* temporal = head;
while (temporal != nullptr) {
std::cout << temporal->value << std::endl;
temporal = temporal->next;
}
}
};
int main() {
LinkedList list;
list.push(1);
list.push(2);
list.push(3);
list.print();
std::cout << "reverse using stack" << std::endl;
list.reverseUsingStack();
list.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment