###Stack - Linear Data Structure, Abstract in nature
Follows LIFO, Last In First Out Ideology
####Abstract ? We know the concept, what stack is. Although it's implementation solely depends on the implementor. For example it can be implemented by arrays, structure or linked list, but what remains common is the type of operations that can be performed over this data-structure - PUSH, POP, TRAVERSE, REVERSE, etc.
- The variable TOP always points to the top of the Stack.
- The variable MAX_SIZE contains the maximum possible size of the Stack.
As mentioned, the implementation can vary and so can the algorithm. One provided here is not meant for efficiency, but for basic Stack implementation.
PUSH(STACK s, element_to_insert):
IF TOP == -1:
/* There's no element in the stack */
s[0] = element_to_insert
TOP = 0
ELSE IF TOP + 1 < MAX_SIZE:
s[TOP + 1] = element_to_insert
TOP = TOP + 1
ELSE
/* There's no more space in the stack */
PRINT "Overflow"
END IF
END PUSH
POP(STACK s):
IF TOP != -1 :
/* If we want to pick a plate from a stack of plates, we pick the topmost one. */
element_fetched = s[TOP]
TOP = TOP - 1
RETURN element_fetched
ELSE
/* Stack's empty. No more elements to fetch. */
PRINT "Underflow"
END IF
END POP
TRAVERSE(STACK s):
IF TOP != -1 :
/* We can easily iterate over the elements to access them */
FOR i = TOP DOWN TO 0:
PRINT s[i]
END FOR
ELSE
/* There's no element in the stack */
PRINT "No elements in the stack"
END IF
END TRAVERSE
REVERSE(STACK s):
IF TOP != -1 :
/* Its quite easy to reverse a stack, if another stack is used. */
/* Pick an element from stack 1 and insert it in stack 2. */
STACK s1 = s
s1_top = TOP
STACK s2
s2_top = -1 /* Initially empty */
WHILE s1_top != -1:
s2_top = s2_top + 1
s2[s2_top] = s1[s1_top]
s1_top = s1_top - 1
END WHILE
/* s2 holds the reverse of STACK s */
TRAVERSE(s2)
ELSE
/* There's no element in the stack */
PRINT "No elements in the stack"
END IF
END REVERSE
For most of the operations here, the complexity will be in order of O(k) [0 < k <= n], where n denotes the Stack size during the concerned moment. Specifically,
- TRAVERSE and REVERSE (using a second stack) will be of O(n)
- while PUSH and POP will be of O(1)