The Stack Eric McCreath
The Stack The stack is a simple but useful data structure in computer science. The stack is an abstract data type that has two main operations. These are push which adds an element to the top of the stack and pop which removes an element from the top of the stack. Push 2 onto Pop off the stack the stack (returning 2) 2 5 5 5 3 3 3 8 8 8 2
The Stack There are a number of stack based machines/languages - e.g. postscript, jvm. Stacks are useful for processing any properly nested structure. e.g. structures that include nested matching brackets "(", ")" , recursive calls to a method, depth-first traversal of a graph. Stacks can be useful for evaluating complex expressions without using a lot of registers. 3
rPeANUt's Stack rPeANUt has a stack pointer and a number of instructions make special use of this register. They include: push <reg> - places the registers value on the top of the stack (this increases the stack pointer). pop <reg> - removes the word from the top of the stack and place the value into the register (decreases the stack pointer). load SP #<off> <reg> - you can also use the base plus displacement load to obtain values on the stack (will not change the stack pointer). store <reg> #<off> SP - this will let you change values on the stack. (also "call", "return", and interrupts make use of the stack but we will look at these in later lectures) 4
Reverse Polish Generally when we write expressions we use "infix" notation. So we may write: Would could also write this using prefix notation (or polish notation). So the same expression becomes: Or in postfix notation (reverse polish): To create the reverse polish of an expression simply do a postorder traversal of its expression tree. 5
Evaluating Expressions Using a Stack Say you have the expression: This could be write in "reverse polish". 2 x * x y * + Evaluation of reverse polish expressions use a stack. To evaluate expressions: literals and variable values are pushed onto the stack. operators pop the values from the stack, do the operation, and push the result back onto the stack. say x=5 and y=3 2 x * x y * + 3 5 5 5 15 2 2 10 25 10 10 10 6
Evaluating Expressions Using a Stack Once an expression is converted to the reverse polish form it can be mechanically converted to code that will evaluate the expression. So the above example would turn into the following code (assume variable x is located at address varx, and variable y at vary): load #2 R0 ; 2 load vary R0 ; y push R0 push R0 load varx R0 ; x pop R0 ; * push R0 pop R1 mult R0 R1 R0 pop R0 ; * push R0 pop R1 mult R0 R1 R0 pop R0 ; + push R0 pop R1 add R0 R1 R0 load varx R0 ; x push R0 push R0 ; the result of the expression is ; now on the top of the stack 7
Exercises Convert the following expression into reverse polish: Implement some rPeANUt code that will evaluate it. 8
Recommend
More recommend