Problem Statement:
Implement Stack
Solution:
Stack supports three main operations:
1. Push:
Insertion of element
2. Pop:
Removal of the last element inserted
3. Peek:
A stack supports LIFO operations i.e. Last In First Out (LIFO)
These all operations are assisted by the "top" pointer which tracks the top most element element in the stack.
References:
Refer to one of my friend's post on stacks: LINK
Please post your comments and suggestions.
Happy Coding !! :)
Implement Stack
Solution:
Stack supports three main operations:
1. Push:
Insertion of element
2. Pop:
Removal of the last element inserted
3. Peek:
A stack supports LIFO operations i.e. Last In First Out (LIFO)
These all operations are assisted by the "top" pointer which tracks the top most element element in the stack.
![]() |
Fig: Stack of books and Stack of Boxes |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | - /** * Stack Implementation * @author Prateek Rathore * */ public class Stack { int arr[]; private static final int DEFAULT_CAPACITY = 10 ; public static int top = - 1 ; public Stack() { arr = new int [DEFAULT_CAPACITY]; } public Stack( int size) { arr = new int [size]; } public void push( int data) { arr[++top] = data; } public int pop() { return arr[top--]; } public int peek() { return arr[top]; } public boolean isEmpty() { if (top==- 1 ) return true ; return false ; } } - |
References:
Refer to one of my friend's post on stacks: LINK
Please post your comments and suggestions.
Happy Coding !! :)
No comments:
Post a Comment