Presentation is loading. Please wait.

Presentation is loading. Please wait.

5. Stacks and Queues.

Similar presentations


Presentation on theme: "5. Stacks and Queues."— Presentation transcript:

1 5. Stacks and Queues

2 Connection to LList Can be implemented as a specialized linked-list
Stacks are LIFO (Last-in-first-out) Adding is called pushing – only happens at end Removing is called popping – also happens at end Queues are FIFO (First-in-first-out) Adding happens at the start Removing happens only at the end.

3 Implementation Strategy #1
Inheritance (“Is-A” relationship) Use extends to inherit from LinkedList Add a redundant push and pop method. - (in Java) can’t hide inherited methods (like insert) + not much work needed. This is the approach taken by: java.util.Queue java.util.Stack public class Stack<E> extends LinkedList<E> { public Stack() { super(); } public void push(E val) { add(val); } public E pop() { remove(size() – 1); } }

4 Implementation Strategy #2
Composition (“Has-A” relationship) Make a new Stack class, add a protected Llist member. + (in Java) we can hide the methods we don’t want to expose - (in Java) more work: we must write wrappers for everything we do want to expose public class Stack<E> { protected LinkedList<E> mList; public Stack() { mList = new LinkedList<E>(); } public void push(E val) { mList.add(val); } public E pop() { mList.remove(size() – 1); } // … every other method we wish to expose }

5 Our Lab One of the first steps in a compiler / interpreter is a syntax check. One important syntax check is brace-matching. Take a language like Lisp (this is version, btw): (exec (= i 0) (= n (input "max: ")) (while (i < n) (exec (if (and (== 0 (% i 3)) (== 0 (% i 5))) (print "FizzBuzz") (if (== 0 (% i 3)) (print "Fizz") (if (== 0 (% i 5)) (print "Buzz") (print i) ) (= i (+ i 1)) ))

6 Our Lab, cont. Do all the parentheses match?
If not, where does the mis-match happen (line & col#)? Note: if we color-code the parens… They have to match from inside-out (exec (= i 0) (= n (input "max: ")) (while (i < n) (exec (if (and (== 0 (% i 3)) (== 0 (% i 5))) (print "FizzBuzz") (if (== 0 (% i 3)) (print "Fizz") (if (== 0 (% i 5)) (print "Buzz") (print i) ) (= i (+ i 1)) ))

7 Our Lab, cont. This is elegantly solved by a stack
…of “Tokens”, where a Token is The character The line it appeared on The position within the line it appeared on Read the file character-by-character If it’s an opening brace: “(“, “{“ or “[“ Create a new token and push it on the stack If it’s a closing brace: “)”, “}” or “]” Look at the top of the stack (peek). If this char matches the one on top (e.g. “{“ matches “}”): pop the top off the stack. If not, we have a syntax error. If we reach the end of the file, but the stack is non-empty, we have one or more syntax.


Download ppt "5. Stacks and Queues."

Similar presentations


Ads by Google