Reverse a link list using stack in C++


Linked list allocates memory dynamically, is used to implement a stack. This program showcase the reversal of the link list in c++ programming. Here, the aspirant can adopt the following approach to get the expected results. The algorithm is as follows;

Algorithm

START
   Step 1: create an empty stack of type node pointer
   Step 2: Traverse the list and push all of its nodes onto a stack
   Step 4: Traverse the list from the head node again
   Step 5: pop a value from the stack top
   step 6: connect them in reverse order
   Step 7: PRINT
STOP

Based on the above algorithm, the following c++ code is drafted where the stdlib library file essay a key role avail the stack related key methods as following;

Example

 Live Demo

#include <iostream>
#include <stdlib.h>
using namespace std;
struct linked_list {
   int data;
   struct linked_list *next;
};
int stack[30], top = -1;
struct linked_list* head = NULL;
int printfromstack(int stack[]) {
   cout<<"\nStack after Reversal::";
   while(top>=0) {
      cout<<stack[top--]<<" ";
   }
}
int push(struct linked_list** head, int n) {
   struct linked_list* newnode = (struct linked_list*)malloc(sizeof(struct linked_list));
   newnode->data = n;
   newnode->next = (*head);
   (*head) = newnode;
}
int intostack(struct linked_list* head) {
   cout<<"Linked list::";
   while(head!=NULL) {
      printf("%d ", head->data);
      stack[++top] = head->data;
      head = head->next;
   }
}
int main(int argc, char const *argv[]) {
   push(&head, 7);
   push(&head, 20);
   push(&head, 3);
   push(&head, 40);
   intostack(head);
   printfromstack(stack);
   return 0;
}

As seen in the above code, all string operation code is bundled into the retrieveChar() method, later on, which call is passed to program main() execution.

Output

Linked list:: 40 3 20 7
Stack after Reversal::7 20 3 40

Updated on: 29-Nov-2019

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements