110 likes | 236 Views
Stack, Queue. Exercise. How can we efficiently implement 2 stacks when it is known that their mutual size does not exceed n? Use a single array of size n. one stack will begin at index 0 and grow up. The second stack will begin at index n-1 and grow down. Balanced expressions.
E N D
Exercise • How can we efficiently implement 2 stacks when it is known that their mutual size does not exceed n? • Use a single array of size n. one stack will begin at index 0 and grow up. The second stack will begin at index n-1 and grow down.
Balanced expressions • We recursively define a well defined expression as: • The series (), [], {} • If a,b are well defined expressions then the expressions (a), [a], {a}, ab are also well defined. • Write an algorithm that efficiently checks if a given input is well defined.
Solution • Initialize an empty stack • While the input has not ended • read the next character • if it is an opening character push it into the stack • else • If the stack is empty return false (missing left bracket) • Otherwise pop the top character from the stack • If the popped character does not fit the current character, return false (the expression is not well defined) • Once the input has ended • if the stack is not empty return false (too many left brackets) • else return true
Solution • Time analysis: each character is read once and pushed and popped from the stack at most one time order of n. • Space analysis: the worst case requires that all the left brackets are in the stack, and there number is at most n O(n)
Implementing a queue using 2 stacks • An inefficient solution • DeQueue () // O(n) while not s1.isEmpty() s2.push(s1.pop()) item s2.pop() while not s2.isEmpty() s1.push(s2.pop()) return item EnQueue(x) // O(1) s1.push(x) isEmpty() // O(1) return s1.isEmpty()
Implementing a queue using 2 stacks • An efficient solution – average dequeue in O(1) • DeQueue () if s2.isEmpty() while not s1.isEmpty() s2.push(s1.pop()) return s2.pop() EnQueue(x) // O(1) s1.push(x) isEmpty() // O(1) return s1.isEmpty() && s2.isEmpty()
Implementing using priority queue • Implement a stack ADT using a heap (priority queue). What is the running time of each operation? • Implement a queue ADT using a heap (priority queue). What is the running time of each operation?
Postfix expressions • Postfix 2 3 + 5 4 + * 2 + • Infix [(2+3) * (5+4)] + 2 • Postfix 2 3 5 * 5 2 + ** • Infix 2 * [(3*5) * (5+2)]
Postfix expressions • Read the input. Each time we encounter an operand push it in the stack. • Each time we encounter an operator, pop the number of expected operands from the stack, perform the operation, and push the result • After parsing the input, the result will be at the top of the stack
Postfix expressions • 7 4 5 3 + 2 * ++ 3 5 4 7 2 8 4 7 16 4 7 207 27