Tuesday, June 24, 2014

Linked List implementation of Stack Data Structure in Java

A stack is a simple data structure for storing data. In stack, the order in which the data arrives is important. A pile of books is a good example of stack. A stack is an ordered list in which insertion and deletion are done at one end, where end is called top. The last element inserted is the first one to be deleted. Hence, it is called Last in First Out (LIFO) or First in Last Out (FILO) list

In this post, we'll see the other way of implementing Stack is by Linked List. This is continuation of the previous post about Array implementation of Stack
In this implementation, push operation is implemented by inserting element at the beginning of the list. Pop operation is implemented by deleting the node from the beginning.
Even you can throw exception instead of printing message in case of pop operation when stack is empty.

Demo
9
8
7
7
false


Generic Implementation of Stack as Linked List
ListNode

Generic Stack

Demo

Performance and Limitations
Performance : Let n be the number of elements in the stack.

  • Space Complexity  for n push operations : O(n)
  • Time Complexity of push : O(1)
  • Time Complexity of pop : O(1)
  • Time Complexity of isEmpty : O(1)
  • Time Complexity of isStackFull : O(1)
  • Time Complexity of deleteStack : O(1)

Limitations : The size of the stack must be defined in prior and cannot be changed.


Download code : ListNode LinkedStack LinkedStackDemo  GenericListNode GenericLinkedStack GenericStackDemo



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

3 comments:

  1. good explanation...But i am not able to copy the code in your post. I think you have used the image for the program. Could you please post the code instead of image..

    Thanks.
    http://javabynataraj.blogspot.com

    ReplyDelete
    Replies
    1. Code is already available at the end of the post.

      Delete
  2. Nice Blog, When i was read this blog i learnt new things & its truly have well stuff related to developing technology, Thank you for sharing this blog.
    iphone job training center
    ios app development course

    ReplyDelete