This is my first post on stack data structure. In this post I am sharing my code of a simple Stack of integers which is internally implemented using integer array.
Stack
A stack is a basic data structure that can be logically thought as
linear structure represented by a real physical stack or pile, a
structure where insertion and deletion of items takes place at one end
called top of the stack. The basic concept can be illustrated by
thinking of your data set as a stack of plates or books where you can
only take the top item off the stack in order to remove things from it.
Basic stack Operations:
Push and Pop
A stack has two fundamental operations - Push and Pop.
The Push operation stores something on the top of the stack and the Pop operation retrives something from the top of the stack. Peek
Peek operation returns top element from the stack without removing it from the stack. Peek is not a fundamental stack operation but it is usually implemented in stack ADT.
Is Empty and Is Full
When stack is empty and pop operation is called then stack should throw "Stack underflow error" and if stack is already full and pop operation is called then we should throw "Stack overflow error".
So as to avoid these two errors we implement Is Empty and Is Full methods. Similar to peek, "Is Empty" and "Is Full" are also not fundamental stack operation.
My Stack Interface
I am creating Stack interface for my Stack ADT. Lets see the code:Array Based Implementation
In an array-based implementation we maintain the following fields:
- an array A of a default size (≥ 1),
- the variable top that refers to the top element in the stack and
- the capacity that refers to the array size.
top = -1
, and the stack is full when top = capacity-1
. The variable top changes from -1 to capacity - 1
.
Below is my code for implementing integer stack using array:
If we run the program we will get output like this:
Please share your
comments if you find anything incorrect, or you want to share more
information about the topic discussed above.
For further reading:
Stack implementation using link list
Stack implementation by link list node,
Stack implementation using doubly link list
Stack implementation by doubly link list node .
For complete listing see data structure and algorithm page
No comments :
Post a Comment