Created
March 5, 2023 23:18
-
-
Save shaobos/87aee5784039af752eddfd22513b9f60 to your computer and use it in GitHub Desktop.
Reverse Linked List - C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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