diff --git a/Linked List/C++/reverse.cpp b/Linked List/C++/reverse.cpp new file mode 100644 index 0000000..24ab1fc --- /dev/null +++ b/Linked List/C++/reverse.cpp @@ -0,0 +1,77 @@ +#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->next = head; + head = temp; + } +}; + +int main() +{ + + LinkedList ll; + ll.push(20); + ll.push(4); + ll.push(15); + ll.push(85); + + cout << "Given linked list\n"; + ll.print(); + + ll.reverse(); + + cout << "\nReversed Linked list \n"; + ll.print(); + return 0; +}