Stacks a data structure which stores data in a Last-in First-out manner (LIFO) has a pointer called TOP can be implemented by either Array or Linked List
Stack top max index = 5 start index = 0 Two operations: PUSH – puts an item on the top of the stack POP – takes an item from the top of the stack 3 is the top of the stack
Stack - pop top What value do we get if we pop from the stack? Answer: 1000
top Stack - pop and the top of the stack changes to ? top Let’s pop once more..
top 2000 is popped… top and top changes to 1 Stack - pop
to what extent do we pop? top Let’s keep popping…
top and now top is 0 let’s pop more..
top and now top is -1 can we still pop? before popping we need to check the top
top pushing an item to stack causes top to move upward first then store the item Stack - push top 5000 To what extent do we push?
Pseudocode for push 1. increment top 2. put item on stack top What if top is the last index? Can we still push? NO !!! when top is max index, we need to signal stack is full
Pseudocode for push 1. increment top 2. put item on stack 3. if top = max index then isFULL=TRUE top Are we done? No, we need to check first if the stack is full Before we proceed to push an item
Pseudocode for push 1. If not isFULL then 2. increment top 3. put item on stack 4. if top = max index then 5. isFULL=TRUE 6. else 7. isFULL = FALSE 8. else 9. display “stack full,push not allowed”
Pseudocode for Pop 1. If not isEmpty then 2. getitem=Stack[top] 3. top=top if top < first index then 5. isEmpty = True 6. else 7. isEmpty=False 8. Else 9. display “stack empty, nothing to pop”
Applications of Stack Checking of balanced parenthesis Tracking memory addresses before and after invoking a function Arithmetic operations evaluation Program compilation
Queue Data structure which stores data in First In – First Out (FIFO)
Queue front rear Two operations: Enqueue – item after the rear Dequeue – get item on the front Did you observe queues in your day to day life?
Queue front rear Enqueue 1.If queue is not full 2. add 1 to rear 3. put item on rear if rear is max index if rear is max index isFull = TRUE isFull = TRUE else else isFull=FALSE isFull=FALSE
front rear Dequeue 1.If queue is not empty 2.get item from front 3.Add 1 to front if front = rear if front = rear isEmpty = TRUE isEmpty = TRUE else else isEmpty=FALSE isEmpty=FALSE Queue
Applications of Queue Printing queue Manage job requests