Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 1052 Stacks 1/11/2019.

Similar presentations


Presentation on theme: "CSC 1052 Stacks 1/11/2019."— Presentation transcript:

1 CSC 1052 Stacks 1/11/2019

2 Outline Stacks Basic operations Examples of use Queues Implementations
Array-based and linked list-based 1/11/2019

3 Static vs. Dynamic Structures
Recall that a static data structure has a fixed size This meaning is different from those associated with the static modifier. Arrays are static; once you define the number of elements it can hold, it doesn’t change. A dynamic data structure grows and shrinks as required by the information it contains.

4 Stacks A stack ADT is linear, like a list or queue, meaning that it maintains its information in a straight line. Items are added and removed from only one end of a stack. It is therefore LIFO: Last-In, First-Out. An Analogy: a stack of plates where the last plate on is the first on off the top.

5 Stacks Stacks are often drawn vertically: PUSH POP add remove

6 A conceptual view of a stack
1/11/2019

7 Stacks Some stack operations:
- push -add an item to the top of the stack. - pop - remove an item from the top of the stack. - peek - retrieves top item without removing it. - empty - returns true if the stack is empty.

8 Stacks A stack is a structure of ordered items such that items can be inserted and removed only at one end - called the Top. A stack is a LIFO or Last-in/First-Out structure. Items are taken out of the stack in reverse order from their insertion. 1/11/2019

9 Non-Computer Examples
Stack of papers Stack of bills Stack of plates Expect O ( 1 ) time per stack operation. (In other words, constant time per operation, no matter how many items are actually in the stack). 1/11/2019

10 Stack The stack specification lists a stack constructor and five methods. One of the simplest stack implementations is to reverse a word. Most compilers use stacks to analyze the syntax of a program. 1/11/2019

11 Using a Stack to reverse a word
Input NAT Push T Using a Stack to reverse a word Push N Push A T A N A N N Pop T Pop A POP N Output TAN A N N 1/11/2019

12 STACKS applications At all times in the execution of the reverse word program, the only item that can accessed from the stack, is the item on TOP. We will use a method called peek() to view the top item Stacks are also used frequently to evaluate expressions so that will be the next application we will look at. 1/11/2019

13 Applications Stacks can be used to check a program for balanced symbols (such as {}, (), []). Example: {()} is legal, {(}) is not (so simply counting symbols does not work). When a closing symbol is seen, it must match the most recently seen unclosed opening symbol. Therefore, a stack will be appropriate. 1/11/2019

14 Balanced Symbol Algorithm
Make an empty stack. Repeatedly read tokens(parenthesis); if the token is: an opening symbol, push it onto the stack If it is a closing symbol and the stack is empty, then report an error; otherwise pop the stack and verify that the popped symbol is a match (if not report an error) At the end of the file, if the stack is not empty, report an error. 1/11/2019

15 Example ( { { Input: { ( ) } Push { Push ( stack now has { (
Pop - Next comes a ) , pop an item, it is ( which matches ). Stack now has { Pop – Next comes a } , pop an item, it is { which matches }. End of file; stack is empty, so all is good. ( { { 1/11/2019

16 Input: ( { } { } ) { { ( ( ( Read 2nd }, pop matching {
Read ) and Pop ( Read and Push ( Read and Push { Read first } , pop matching { Read and Push 2nd { Empty Stack { ( { ( ( ( ( 1/11/2019

17 Input: [ { } { } ]{} { And so on.. { [ [ [ 1 2 3 4 [ [ 5 6
Initial Empty Stack Read and Push [ Read and Push { Read first }, pop matching { { [ [ [ 1 2 3 4 Read and Push 2nd { Read 2nd }, pop matching { { And so on.. [ [ 5 6 1/11/2019

18 Performance Running time is O( N ), where N is amount of data (that is, number of tokens). Algorithm is online: it processes the input sequentially, never needing to backtrack. 1/11/2019

19 Balancing an expression
In the method IsBalanced(String exp) an expression is checked to see if all the parentheses match. A charStack is set up whose legal characters are: “() {} [} “ A switch is used 1/11/2019

20 Method Stack Matching symbols is similar to method call and method return, because when a method returns, it returns to the to the method that called it. A method stack can be used to keep track of this. Abstract idea: when a method call is made, save current state on a stack. On return, restore the state by popping the stack. 1/11/2019

21 Stack Frames or Activation Records
Programs compiled from modern high level languages make use of a stack frame for the working memory of each method invocation. When any method is called, a number of words - the stack frame - is pushed onto a program stack. When the method returns, this frame of data is popped off the stack. 1/11/2019

22 Stack frame or Activation Record
Frame contains: Method arguments Return address Local variables 1/11/2019

23 method f( int x, int y) { int a; if ( term_cond ) return …; a = …
method f( int x, int y) { int a; if ( term_cond ) return …; a = ….; return g( a ); } method g( int z ) { int p, q; p = …. ; q = …. ; return f(p,q); } Context for execution of f: Each frame contains parameters, return address and local variables 1/11/2019

24 Activation Records As a method calls another method, first its arguments, then the return address and finally space for local variables is pushed onto the stack. Actual implementation is slightly different . The top of stack can store the current method environment. When method is called, the new environment is pushed onto stack. On return, the old environment is restored by popping the method environment. 1/11/2019

25 Stack Frames Ø Since each function runs in its own "environment" or context, it becomes possible for a function to call itself - a technique known as recursion. Ø This capability is extremely useful and extensively used - because many problems are elegantly specified or solved in a recursive way. 1/11/2019

26 Stack Frames The most common applications for stacks have a space restraint so that using an array implementation is a natural and efficient one. (In most operating systems, allocation and de-allocation of memory is a relatively expensive operation, there is a penalty for the flexibility of linked list implementations.). 1/11/2019

27 Array Implementations
Stacks can be implemented with an array and an integer top that stores the array index of the top of the stack. Empty stack has top equal to -1. To push, increment the top counter, and write in the array position. To pop, decrement the top counter. 1/11/2019

28 Stages A B top(1) top(-1) A top(0) 1/11/2019

29 Array Doubling If the stack is full (because array size has been reached), we can extend the array, using array doubling. We allocate a new, double-sized array and copy contents over: TempArray =[T] new Object[ OldArray.length * 2 ]; for( int j = 0; j < OldArray.length; j++ ) TempArray[ j ] = OldArray[ j ]; OldArray = TempArray; 1/11/2019

30 Running Time Without array doubling, all operations are constant time, and do not depend on number of items in the stack. With array doubling, a push could occasionally be O( N ). However, if the array doubling occurs infrequently, it is essentially O( 1 ) because each array doubling that costs N assignments is preceded by N/2 non-doubling pushes. 1/11/2019

31 Expression Evaluation
1/11/2019

32 Examples 4-4-4 evaluates to -4 2^2^3 evaluates to 256
Parenthesis override precedence and associativity. Regular expressions can be changed into postfix and then solved. After the regular expression is changed to postfix it is easier to solve than directly solving and regular(infix) expression 1/11/2019

33 Postfix Expressions To evaluate a postfix expression:
scan from left to right, determining if the next token is an operator or operand if it is an operand, push it on the stack if it is an operator, pop the stack twice to get the two operands, perform the operation, and push the result onto the stack At the end, there will be one value on the stack, which is the value of the expression 1/11/2019

34 Postfix Example 1 2 3 * + Push 1, Push 2, Push 3.
When * is seen, Pop 3, Pop 2, evaluate 2 * 3, and Push the result 6. When + is seen, Pop 6, Pop 1, evaluate 1 + 6, and Push the result 7. At end of expression, stack should have one item, which is the answer. 1/11/2019

35 Postfix Example, Continued
The following operations will store the expression on the stack. As an operator is encountered the operators are popped and the appropriate operation performed. 1 2 3 * + 7 1 2 3 6 Push 1 Push 2 Push 3 Pop 3 Pop 2 Push 6 Pop 6 Pop 1 Push 7 1/11/2019

36 OLD COMPILERS translated infix expressions using two stacks into machine language.
AN OPERATOR IS PLACED BETWEEN ITS OPERANDS c – d + (e * f – g * h) / i INFIX MACHINE LANGUAGE THIS GETS MESSY BECAUSE OF PARENTHESES and need for two stacks NEWER COMPILERS: INFIX POSTFIX MACHINE LANGUAGE 1/11/2019

37 IN POSTFIX NOTATION, AN OPERATOR IS PLACED
IMMEDIATELY AFTER ITS OPERANDS. INFIX POSTFIX a + b ab+ a + b * c abc*+ a * b + c ab*c+ (a + b) * c ab+c* PARENTHESES NOT NEEDED – AND NOT USED – IN POSTFIX 1/11/2019

38 The LinkedStack Class Now let's examine a linked implementation of a stack We will reuse the LinearNode class that we used in LinkedList implementation to define the linked implementation of a set collection Internally, a stack is represented as a linked list of nodes, with a reference to the top of the stack and an integer count of the number of nodes in the stack 1/11/2019

39 A linked implementation of a stack
1/11/2019

40 LinkedStack - the push Operation
1/11/2019

41 The stack after pushing element E
1/11/2019

42 ArrayStack - the pop Operation
1/11/2019

43 The stack after a pop operation
1/11/2019

44 The ArrayStack Class Now let's examine an array-based implementation of a stack We'll make the following design decisions: maintain an array of T references the bottom of the stack is at index 0 the elements of the stack are in order and contiguous an integer variable top stores the index of the next available slot in the array This approach allows the stack to grow and shrink at the higher indexes 1/11/2019

45 An array implementation of a stack
1/11/2019

46 ArrayStack - the push Operation
// // Adds the specified element to the top of the stack, expanding // the capacity of the stack array if necessary. public void push (T element) { if (size() == stack.length) expandCapacity(); stack[top] = element; top++; } 1/11/2019

47 The stack after pushing element E
1/11/2019

48 ArrayStack - the pop Operation
// // Removes the element at the top of the stack and returns a // reference to it. Throws an EmptyStackException if the stack // is empty. // public T pop() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException(); top--; T result = stack[top]; stack[top] = null; return result; } 1/11/2019

49 The stack after popping the top element
1/11/2019

50 A UML description of the java.util.Stack class
1/11/2019

51 Analysis of Stack Operations
Because stack operations all work on one end of the collection, they are generally efficient The push and pop operations, for both linked and array implementations, are O(1) Likewise, the other operations for all implementations are O(1) We'll see that other collections (which don't have that characteristic) aren't as efficient for all operations 1/11/2019

52 Collections Framework
Let’s review more about the properties that all the collection classes have in common: Allow the collection size to increase dynamically All only hold items of class of generic T Provides at least two contructors – one to create an empty collection and one that accepts as a parameter any other collection object and creates a new collection object that holds the same information. 1/11/2019

53 Collections Framework
The collections differ in: Logical structure of the elements they contain The underlying implementation’ The efficiency of the various operations The set of supported operations Whether they allow duplicates Whether they allow keys Whether the elements are sorted 1/11/2019

54 Collections Framework
The Vector class has been replaced by the ArrayList class which provides the same methods in a single thread environment. The HashTable class also supports synchronization so for single thread programs you should use HashMap. The Stack class of the Collections Framework is implemented with a Vector. There are the expected problems with performance due to concurrency and a logical error. Vectors allow access anywhere in the array, stacks do not. 1/11/2019

55 Collections Framework
The Collection Interface is used by classes that do not support a unique key value, e.g. unkeyed lists and sets. Some methods in the interface are: boolean Add(T obj) - adds obj to Collection boolean addAll(Collection c) –add c to Collection boolean contain(T obj) – return true if obj is in Collection boolean isEmpty() - returns true if collection is empty 1/11/2019

56 Collections Framework
The MAP interface:: This interface is used by library collection classes that map unique keys to values. It defines a a method to retrieve an object based on its key value. Classes that implement the MAP interface are: AbstractMap, HashMap and HashTable. 1/11/2019

57 Collections Framework
The AbstractCollection Class implements the Collection interface. The Collection interface defines 15 operations Some of these methods define fundamental operations which will vary with the particular collection. Others will be the same no matter what the implementation, e.g. The size method will depend upon the implementation so it is an abstract method but the isEmpty() method can be implemented as: public boolean isEmpty() { return (this.size() == 0) } 1/11/2019

58 Collections Framework
By defining as many methods as possible in terms of the fundamental operations, the AbstractCollection class cuts down on the time to implement a new collection. In addition, two other abstract classes extend the AbstractCollection class – AbstractSet and AbstractList. Both these classes perform the same services as the AbstractCollection class Finally, concrete classes extend AbstractSet and AbstractList. 1/11/2019

59 1/11/2019


Download ppt "CSC 1052 Stacks 1/11/2019."

Similar presentations


Ads by Google