Be the first user to complete this post

  • 0
Add to List
Beginner

193. Implement Stack Using Linked List

Objective: Write an algorithm to implement Stack using Linked List.

If you do not know about then for starters it's an abstract data type that follows the principle of LIFO (Last-In-First-Out) which means the data goes in last and comes out first read about it in detail please read this link Stack

Approach:

The solution is quite simple, Earlier we saw the article  "Linked List Implementation", we need to make some changes to make it work as Stack.

Stack Operations:

Push(): Insert the element into the linked list at the beginning and increase the size of the list. O(1) operation.

Pop(): Return the element's first node from the linked list and move the head pointer to the second node. Decrease the size of the list. O(1) operation.

getSize(): Return the size of the linked list.

displayStack(): Print the linked list.

 

Output:

Element 1 is pushed into Stack
Element 2 is pushed into Stack
Element 4 is pushed into Stack
4 2 1
Pop out element 4
2 1

Note: Also read, Track the Maximum Element in a Stack. This problem was asked in Yahoo in Software Engineer position.