3
Stacks A stack is a LIFO (Last In First Out) list of elements. Operations allowed in a stack: Addition (Push) Deletion (Pop) Inspect Top Allowed at the end of the list, known as stacktop. Real-life examples of stacks are very common. Here are a few: A stack of dishes, A stack of paper, A stack of books. 3

4
Graphically Additions and Deletions at the stacktop 4

5
Balanced Parentheses Checking Given a string of Open “(” parentheses, and Closed “)” parentheses. An interesting problem: To design an algorithm that checks if balanced. When is a string of parentheses balanced? If it is either of the form: (s) s()or ()s wheres is a string of balanced parentheses, or the empty string. 5

7
Goal We want to design a stack-based algorithm that checks if a string of parentheses is balanced. How does it work? Scan the string from left to right. If character is opening bracket Push it onto the stack. If character is closing bracket, and stack is empty The string is not balanced. Otherwise Pop the opening bracket from stack. If scanning ends and stack is not empty The string is not balanced. 7

8
Example The string ((()(())()) is not balanced. An opening bracket will be left on the stack. The string )() is not balanced either. A closing bracket found and stack is empty. The string (()) is balanced. Both scanning will end and stack will be empty. 8

9
Postfix Arithmetic Expression Evaluation Three ways of writing arithmetic expressions: Prefix: + a b Operands are preceded by operator. Infix: a + b Usual way of writing: Operand, then Operator, and finally Operand. Postfix: a b + Operands are followed by operator. 9

11
Postfix Expression Evaluation Algorithm is simple: Scans characters in given expression from left to right. If character is an operand Push it onto stack If character is an operator Pop two operands from stack. Apply operator to these two operands. Push the result onto stack. 11

17
Reversing Digits of a Number A very interesting problem. It involves the use of stacks. Given a non-negative integer, n. Want to output a number m … whose digits are the reverse of those of n. For example: Input is n = 1234 Output is m = 4321 An algorithm for this problem? 17

20
Time Complexity of Algorithm ReverseDigit Assumption: Let k be the number of digits in the value n Operators div, mod, + and * take constant time, O(1) Number of steps of first while loop: 2 * k Number of steps of second while loop: 3 * k Also, k = log 10 n But, we know that log 10 n = log 2 n / log 2 10, and log 2 10  3.32 Then, 20

21
Queues A queue is a FIFO (First In First Out) list of elements. It is a close “cousin” of the stack Addition to this list (Enqueue) is done at one end, called the BACK of the queue. Deletion (Dequeue) is done at the other end, called the FRONT of the queue. Graphically: 21

22
Real-life examples of queues A queue at a bus-stop A line at a bank machine A printer queue Food for thought: A bank has three tellers. Would it be better to have a queue for each teller, or one queue that feeds all three tellers. How could you set up an experiment to test your hypothesis? 22

23
Application of Queues: Pathfinding Start Finish 23 A rat, started off at the START square of the maze. Has to find the shortest path to the FINISH square. Shaded squares are blocked off to the rat. Length of path is the number of squares the rat visits.

24
Using a queue From a given square, the rat can move left, right, up or down. Assumption: “our” rat knows about the data structure. It does the following: It labels all the squares it can visit, from the START square being number 0, and saves positions at the back of the queue. Then, it takes all positions (coordinates) from the front of queue, and Assuming this position is labeled i, It marks all positions it can visit with i + 1 It continues until it visits the FINISH square. 24

25
Finding the shortest path It does this by moving backwards, as follows. If the FINISH square would have been labeled k, It moves back to square labeled k – 1, then, to a square labeled k – 2, and so on, until it reaches the START square. Each move is possible, since to reach square k one would have to reach square k – 1 25

27
Array Implementations of a Queue Some problems arise in implementing a queue when using an array Let’s see a solution (Fixed Front Approach): Fix the front of the queue at 0 Let the back be movable. frontback

28
Time complexity of enqueue and dequeue? Enqueue operation: Takes constant, O(1), time. Why? Very simple: Assign element to A[back] Set back to back + 1 = 7 Dequeue operation: Takes linear, O(n), time. Why? Complicated: Shift elements A[1]..A[back-1] one position to the left. Set back to back - 1 Quite inefficient!!! 28

29
Moveable Front Approach Can we do better? Yes… Make the front of the queue movable as well. front back

30
Time complexity of enqueue and dequeue? Enqueue operation: Takes constant, O(1), time. Why? Very simple: Assign element to A[back] Set back to back + 1 = 9 Dequeue operation: Takes constant, O(1), time !!! Why? Easy: Assign A[front] to element Set front to front + 1 Much more efficient, but… still a problem… 30

31
Problems We need to keep lots of unused positions: On the right of array … to enqueue. And, will have lots of unused positions: on the left of the array … after dequeueing. Still BIG Problems: Lots of unused positions in the array. Queue may become full, and still unused positions on the left! 31

32
Can we do even better? Circular array based Yes… Implement A “circular” queue, or a “circular” array. We will have two configurations… Normal configuration: front < back front back

35
Implementation To dequeue: If (queue not empty) Increment front as: (front + 1) mod N Queue empty? … when back = front Now, unused cells will be: at the extremes of the array, or in the middle portion of the array. 35

36
Time complexity of enqueue and dequeue? Enqueueing: Constant time, O(1). Dequeueing: Constant time, O(1), too!!! Note: full queue still has one wasted slot. It is possible to design this so no slots are wasted by keeping a separate count variable to distinguish empty and full. 36

37
Singly linked lists A typical example of a linked list: Every node can be accessed via first. Each node has a link to the next element. 37

38
Doubly linked Lists A typical example: In a doubly linked list, we have: Two “unused” nodes for first and last – Why?. Every node in List can be accessed: either via first or via last Each node has two links: next element, previous element 38

39
Inserting an element Find the node … after which element is to be inserted. Create a new node Set the new node’s element to element Establish the corresponding links: Set next of node and prev of next of node to new node We can start searching from first, or can start from last Here is the an algorithm starting from first … 39

41
Example: Insert last Observations: How does it work starting from last? Homework… Other types of objects can be stored in the list. Examples: Strings, float’s, double’s, or even any Object.

42
Time complexity of Algorithm InsertElement While loop is executed at most n times, where n is the number of elements Thus, it takes O(n) to find and insert the element. Insertion only takes O(1) !!! What is time complexity if we started from last? Homework… What if we had an array instead? Find takes O(n) and then insert takes O(n) too. Also, an advantage of using a linked list: Array’s size is fixed, and list’s is not. 42

43
Advantage of using doubly linked lists If the list is sorted, and  want to find the maximum (or minimum) of the list: it takes O(n) in a linked list, and O(1) in a doubly linked list! For any order of elements:  want to insert an element at the end: it takes O(n) in a linked list, whereas in a doubly linked list: O(1) 43

44
Deleting an element Find the node … containing element to be removed. Just modify the corresponding links: Change next of previous of node and previous of next of node What does the algorithm look like? Again, we can start from first, or can start from last Here is the algorithm starting from first: 44

46
Example: Delete Observations: How does it work starting from last? Homework … What is time complexity of DeleteElement? …

47
Time complexity of DeleteElement Again, To find the element, it takes O(n) (the while loop in Algorithm DeleteElement) But, To delete the element, it takes O(1) In an array implementation: It takes O(n) just to delete the element!! Why? Homework: Write the algorithm that starts from last. 47