Skip to content

Instantly share code, notes, and snippets.

@shaobos
Created March 5, 2023 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaobos/87aee5784039af752eddfd22513b9f60 to your computer and use it in GitHub Desktop.
Save shaobos/87aee5784039af752eddfd22513b9f60 to your computer and use it in GitHub Desktop.
Reverse Linked List - C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
void add(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void reverse() {
// TODO: implement
}
void print() {
Node* current = head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
cout << "Original list: ";
list.print();
list.reverse();
cout << "Reversed list: ";
list.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment