diff --git a/C++/RevLinkedList.cpp b/C++/RevLinkedList.cpp new file mode 100644 index 0000000..cec7b84 --- /dev/null +++ b/C++/RevLinkedList.cpp @@ -0,0 +1,77 @@ +// Iterative C++ program to reverse a linked list +#include +using namespace std; + +/* Link list node */ +struct Node { + int data; + struct Node* next; + Node(int data) + { + this->data = data; + next = NULL; + } +}; + +struct LinkedList { + Node* head; + LinkedList() { head = NULL; } + + /* Function to reverse the linked list */ + void reverse() + { + // Initialize current, previous and next pointers + Node* current = head; + Node *prev = NULL, *next = NULL; + + while (current != NULL) { + // Store next + next = current->next; + // Reverse current node's pointer + current->next = prev; + // Move pointers one position ahead. + prev = current; + current = next; + } + head = prev; + } + + /* Function to print linked list */ + void print() + { + struct Node* temp = head; + while (temp != NULL) { + cout << temp->data << " "; + temp = temp->next; + } + } + + void push(int data) + { + Node* temp = new Node(data); + temp->next = head; + head = temp; + } +}; + +/* Driver code*/ +int main() +{ + /* Start with the empty list */ + LinkedList l; + l.push(2); + l.push(4); + l.push(1); + l.push(8); + + cout << "Given linked list\n"; + l.print(); + + l.reverse(); + + cout << "\nReversed linked list \n"; + l.print(); + return 0; +} + +