From 9c0d0483ce5b5d48561c5d832659c73d4237f6d2 Mon Sep 17 00:00:00 2001 From: divyansh739 <115534606+divyansh739@users.noreply.github.com> Date: Sat, 22 Oct 2022 19:15:10 +0530 Subject: [PATCH] Create divyansh.dsa --- divyansh.dsa | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 divyansh.dsa diff --git a/divyansh.dsa b/divyansh.dsa new file mode 100644 index 0000000..9c04751 --- /dev/null +++ b/divyansh.dsa @@ -0,0 +1,74 @@ +#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 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; +}