Stack
Stack is one of the elementary data structure in which elements are added and deleted using Last-In-First-Out (LIFO) principle. To understand LIFO principle, let us consider a teacher is checking the examination paper. After checking each paper, he/she keeps the papers by his/her side such that the first paper checked, remained at the bottom and the last paper checked, remained at the top. So, the paper is inserted at the top of the pile of paper. While distributing the examination paper, the first paper to be removed, is the one which was on the top of the pile. This is known as LIFO principle.
Here, we will see the implementation of stack using an array. Let, S[1…n] be the array. The stack has an attribute, S.top which gives index of the most recently added element. The stack is empty if S.top = 0. The insert and delete operation in the stack has special names, push and pop respectively. If we try to push an element in the stack containing n elements, an error occurs which is known as stack overflow. Similarly, if we try to pop an empty stack, stack underflow occurs. Now, let’s see the operations in the stack.
STACK_EMPTY(S)
if S.top == 0
return True
else
return False
STACK_PUSH(S, x)
if S.top == n
Error “Stack Overflow”
else
S.top = S.top + 1
S[S.top] = x
STACK_POP(S)
if STACK_EMPTY(S)
Error “Stack Underflow”
else
S.top = S.top – 1
return S[S.top + 1]
If we analyze the running time of each operation, we can see that each of the operations take O(1) time. O(1) time simply means that the time required is constant and it does not change even if the size of the array is made large. Every modern programming languages have the library facility to implement stack. For example, in C++, you can use Standard Template Library (STL) to implement stack. Now, let’s consider a simple operation in which we can use stack. Suppose we have to take the input from the user and print it in reverse form. Then, we can use stack to store the input then, pop the value from the stack. Algorithm to print the input from the user in reverse form
while (input != newline)
Store input in variable x
STACK_PUSH (S, x)
while(!STACK_EMPTY)
x = STACK_POP (S) //pops value from the stack and store it in variable x
Output x
In the above algorithm, if the input is in the sequence 1 2 3 4 5 then, the output will be 5 4 3 2 1.
Reference book:
Introduction to Algorithms by CLRS
Comments
Post a Comment