DATA STRUCTURE AND ALGORITHMS Lecture 2 Tahir Iqbal
Introduction to STACKS Week 2
STACKS A stack is a linear list in which insertion and deletion take place at the same end This end is called top The other end is called bottom Stacks are known as LIFO (Last In, First Out) lists. The last element inserted will be the first to be retrieved E.g. a stack of Plates, books, boxes etc.
OPERATION ON STACK Creating a stack Checking stack---- either empty or full Insert (PUSH) an element in the stack Delete (POP) an element from the stack Access the top element Display the elements of stack Emptying a stack
S TACK ADT A linear list in which insertion and deletion take place at the same end (i.e. top) Elements: Top element Rest of Stack Last-In-First-Out (LIFO) Operations: createStack() isFull() isEmpty() Push() Pop() displayTop() displayStack() emptyStack()
I NSERTION AND DELETION ON STACK
PUSH AND POP Primary operations: Push and Pop Push Add an element to the top of the stack. Pop Remove the element at the top of the stack.
STACK-RELATED TERMS Top A pointer that points the top element in the stack. Stack Underflow When there is no element in the stack, the status of stack is known as stack underflow. Stack Overflow When the stack contains equal number of elements as per its capacity and no more elements can be added, the status of stack is known as stack overflow
STACK IMPLEMENTATION Implementation can be done in two ways Static implementation Dynamic Implementation Static Implementation Stacks have fixed size , and are implemented as arrays It is also inefficient for utilization of memory Dynamic Implementation Stack grow in size as needed, and implemented as linked lists Dynamic Implementation is done through pointers The memory is efficiently utilize with Dynamic Implementations
S TATIC I MPLEMENTATION Linear array STACK (to store elements of stack) . A pointer variable TOP (pointing towards the location of top element). TOP =0 or NULL ->indicates that stack is empty A variable MAXSTK (giving the capacity of stack)
S TATIC IMPLEMENTATION PUSH Procedure: PUSH(STACK, TOP, MAXSTK, ITEM) (This procedure pushes an ITEM onto a stack) 1. [Stack already filled?] If TOP = MAXSTK, then: Print OVERFLOW, and Return. 2. Set TOP := TOP + 1. [Increases TOP by 1] 3. Set STACK[TOP] := ITEM. [Inserts ITEM in new TOP position] 4. Return
S TATIC IMPLEMENTATION POP Procedure: POP(STACK, TOP, ITEM) (This procedure deletes the top element of stack and assigns it to the variable ITEM) 1. [Stack has an ITEM to be removed?] If TOP = 0, then: Print UNDERFLOW, and Return.
- Fall '17
- Tahir Iqbal