This post is completed by 3 users

  • 0
Add to List
Medium

551. Reverse a linked list using stack

Given a linked list, write a function to to reverse the linked list using stack.

Example:

Original List :->10->8->6->4->2
Reversed List :->2->4->6->8->10

Approach: Stack

Earlier we had solved this problem using Recursion, in this post we are going to solve it using stack.

Steps:

  • Initialize a Stack.
  • Iterate the linked list and insert all the nodes in the stack. Note that the last node in the linked list will be at the top of the stack and this node becomes the head of the linked list.
  • Take all the nodes out from stack, make top node as head and for rest of the nodes, keep adding to the head. (Since Stack is LIFO, all the nodes will be added to the head in the reverse order.
  • Return the head.

Complete Code:

Output:

Original List :
->10->8->6->4->2
Reversed List :
->2->4->6->8->10