Stack is a linear Data Structure that is based on the LIFO concept (last in first out). Instead of only an Integer Stack, Stack can be of String, Character, or even Float type. There are 4 primary operations in the stack as follows:
- push() Method adds element x to the stack.
- pop() Method removes the last element of the stack.
- top() Method returns the last element of the stack.
- empty() Method returns whether the stack is empty or not.
Note: Time Complexity is of order 1 for all operations of the stack
let s = empty stack of Integer type with size 4
push (100) : top = top + 1 and s[top] = 100
push (200) : top = top + 1 and s[top] = 200
push (300) : top = top + 1 and s[top] = 300
pop ( ) : top = top - 1
push (500) : top = top + 1 and s[top] = 500
push (600) : top = top + 1 and s[top] = 600
Note:push (700) : top +1 == size of stack : Stack Overflow ! // Since top = 3 and size of stack = 4, no more elements can be pushed
s1 after pushing 10, 20 and 30 : 10->20->30 s1 after pop : 10->20 s2 after pushing 3 elements : hello->world->java s2 after pushing 4th element : Stack Overflow s3 after pushing 2 elements : 100.0->200.0 top element of s3: 200.0
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.