The Stack Data Structure

Introduction

 A stack is an ordered collection of items into which insertion and deletion operations occurs at only one end, called top of the stack (TOS). Unlike that of the array, the definition of stack provides for the insertion and deletion of items so that stack is dynamic and constantly changing object. 

Stacks are the subclass of lists that permits the insertion and deletion

operation to be performed at only one end.

So, how does stack change? The definition of stack specifies that a single end which is designated as the stack top. New items may be put on top of the stack where TOS moves upward and items which are at top of the stack may be removed in which TOS moves downward. 

stack data structure


Here insertion and deletion is done from the same end, last element inserted will be the first element to be removed out of the stacks resulting FILO (First In Last Out) or LIFO (Last In First Out). It can be implemented into two ways:

1. Static implementation

    - Using array

2. Dynamic implementation 

    - Using linked list


Operations on stacks

A pointer TOS keeps track of the top element in stack. Initially when stack is empty, TOS is equals to -1 and when stack contains a single element, TOS has value of zero and so on. Each time a new element is inserted in the stack, the pointer TOS is incremented by one before the element is placed in the stack. The pointer is decremented when deletion is made from the stack. Here max is define for the maximum size of stack in case of static implementation. Then the following operations can be carried out:

1. isFull()

Check whether the stack is full or not.
  1. if TOS == max-1, return true
  2. else return false

2. isEmpty()

Check whether the stack is empty or not.
  1. if TOS == -1, return true
  2. else return false

3. push()

Insert new element at new position of TOS.
  1. if isFull(), then display "stack is full" and stop
  2. read data
  3. TOS = TOS + 1
  4. stack [TOS] = data
  5. stop

4. pop()

Delete element from TOS.
  1. if isEmpty(), then display "stack is empty" and stop
  2. item = stack [TOS]
  3. TOS = TOS - 1
  4. return item

Application of Stack

  • Used to process function calls
  • Implementing recursive functions in high level languages
  • To check the validity of an arithmetic expression
  • Evaluating and converting the mathematical expression
  • Counting parenthesis and matching nested parenthesis
  • Maintaining browsing history
  • For undo operations
  • String reversing
  • Interop handling in microprocessor etc.

Comments

Popular posts from this blog

Abstract Data Type ( ADT ) and Abstraction

Data Structures and Algorithms : Introduction, Type and Uses

What is Algorithm? and its types