From 8b13dd376754e9a4e576588485443411bfb3c241 Mon Sep 17 00:00:00 2001 From: Aryan Date: Sat, 15 Oct 2022 17:44:53 +0530 Subject: [PATCH] Added a c++ code for reversing a linked list --- C++/reverse_linked_list.cpp | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 C++/reverse_linked_list.cpp diff --git a/C++/reverse_linked_list.cpp b/C++/reverse_linked_list.cpp new file mode 100644 index 0000000..bbc581b --- /dev/null +++ b/C++/reverse_linked_list.cpp @@ -0,0 +1,58 @@ +#include + +using namespace std; + +struct node { + int data; + struct node *next; +}; + +// To create a demo we have to construct a linked list and this +// function is to push the elements to the list. +void push(struct node **head_ref, int data) { + struct node *node; + node = (struct node*)malloc(sizeof(struct node)); + node->data = data; + node->next = (*head_ref); + (*head_ref) = node; +} + +// Function to reverse the list +void reverse(struct node **head_ref) { + struct node *temp = NULL; + struct node *prev = NULL; + struct node *current = (*head_ref); + while(current != NULL) { + temp = current->next; + current->next = prev; + prev = current; + current = temp; + } + (*head_ref) = prev; +} + +// To check our program +void printnodes(struct node *head) { + while(head != NULL) { + cout<data<<" "; + head = head->next; + } +} + +// Driver function +int main() { + struct node *head = NULL; + push(&head, 0); + push(&head, 1); + push(&head, 8); + push(&head, 0); + push(&head, 4); + push(&head, 10); + cout << "Linked List Before Reversing" << endl; + printnodes(head); + reverse(&head); + cout << endl; + cout << "Linked List After Reversing"<