Transcript Slide 1

1

CS212: DATA STRUCTURES

Computer Science Department Lecture 6: Stacks

Lecture Contents

2

 What is Stack ?

 Basic Stack Operation  Array-Based Stack Implementation  Stack Linked List Implementation  Infix, Postfix and Prefix 29-Apr-20 Computer Science Department

3

Stacks

What is Stack ?

 A Stack is a linear list in which all additions and deletions are restricted to one end ,called the top  Objects can be inserted into a stack at any time, but only the most recently inserted (that is, "last") object can be removed at any time. 29-Apr-20 Computer Science Department

4

Stacks

?

What is Stack  If you inserted a data series into a stack and then removed it ,the order of the data would be reversed .

 Data input as {5,10,15,20} would be removed as {20,15,10,5}  This reversing attribute is why stacks are known as last in first out(LIFO) 29-Apr-20 Computer Science Department

5

Stacks

Example 1:

 Internet Web browsers store the addresses of recently visited sites on a stack. Each time a user visits a new site, that site's address is "pushed" onto the stack of addresses. The browser then allows the user to "pop" back to previously visited sites using the "back" button. 29-Apr-20 Computer Science Department

6

Stacks

Example 2:

 Text editors usually provide an "undo" mechanism that cancels recent editing operations and reverts to former states of a document. This undo operation can be accomplished by keeping text changes in a stack.

29-Apr-20 Computer Science Department

Abstract data types (ADTs)

abstract data type (ADT): A specification of a collection of data and the operations that can be performed on it.

 Describes what a collection does, not how it does it   We don't know exactly how a stack is implemented, and we don't need to.

 We just need to understand the idea of the collection and what operations it can perform.

Formally, a stack is an abstract data type (ADT) that supports the following two methods:

8

Stacks

Basic Stack Operation 1.Push

 Add new element to the top of the stack  The input consists of the stack and the new element.

 Prior to this operation, the stack must exist and must not be full 29-Apr-20 Computer Science Department

Top

Stacks

Data

Push

operation Check for enough room, (no overflow) Top 9

10

Stacks

Basic Stack Operation 2. Pop

 Removes the top element of the stack.  Prior to this operation, the stack must exist and must not be empty.

29-Apr-20 Computer Science Department

Top

Stacks

Check if empty, (no underflow) Data

Pop

operation Top 11

12

Stacks

Other Stack Operation

 Additionally, let us also define the following methods:  size(): Return the number of elements in the stack.  isEmpty(): Return a Boolean indicating if the stack is empty. 29-Apr-20 Computer Science Department

13

Stacks

Other Stack Operation

Top:

 Returns the top element of the stack.

 Prior to this operation, the stack must exist and must not be empty.

29-Apr-20 Computer Science Department

Top

Stacks

Check if empty, (no underflow) Data

Stack top

operation Top 14

Exceptions

15

 Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception  Exceptions are said to be “thrown” by an operation that cannot be executed  In the Stack ADT, operations pop and top cannot be performed if the stack is empty  Attempting the execution of pop or top on an empty stack throws an EmptyStackException 29-Apr-20 Computer Science Department

Class Stack

Stack<

E

>() push(

value

) pop() top() size() isEmpty() constructs a new stack with elements of type

E

places given value on top of stack removes top value from stack and returns it; throws EmptyStackException if stack is empty returns top value from stack without removing it; throws EmptyStackException if stack is empty returns number of elements in stack returns true if stack has no elements Stack s = new Stack(); s.push(42); s.push(-3); s.push(17);

// bottom [42, -3, 17]

System.out.println(s.pop());

// 17

17

Array-Based Stack Implementation

 We can implement a stack by storing its elements in an array. Specifically, the stack in this implementation consists of an N-element array S plus an integer variable t that gives the index of the top element in array S.

29-Apr-20 Computer Science Department

Array-Based Stack Implementation

con..

0 1 2 3 4 5 6 7 8 9 stk: 17 23 97 44 top = 3 or count = 4    If the bottom of the stack is at location 0 , then an empty stack is represented by top = -1 or count = 0 To add ( push ) an element, either:   Increment top and store the element in Store the element in stk[count] stk[top] and increment , or count To remove ( pop ) an element, either:   Get the element from Decrement count stk[top] and decrement and get the element in top stk[count] , or 18

19

Array-Based Stack Implementation

con..

 The array implementation of a stack is simple and efficient. Nevertheless, this implementation has one negative aspect—it must assume a fixed upper bound, CAPACITY, on the ultimate size of the stack. 29-Apr-20 Computer Science Department

Array-Based Stack Implementation

con..

20

 Fortunately, there is another implementation, which we discuss next, that does not have a size limitation and use space proportional to the actual number of elements stored in the stack. 29-Apr-20 Computer Science Department

21

Linked-list implementation of stacks

  Several data strucures could be used to implement a stack.

To implement linked list stack , we need two different structures , a head and a data node.

Head count Top Top 29-Apr-20 (a) Concep tual Computer Science Department

Linked-list implementation of stacks

con..

22

   Stack Head :require only two attributes top pointer count for number of elements in the stack 

Stack Data Node

The rest of the data structure is a typical linked list data

node

The header of the list points to the top of the stack myStack: 44 97 23 Pushing is inserting an element at the front of the list 17

23

Infix, Postfix and Prefix

Infix, Postfix and Prefix

 Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions.  It is easiest to demonstrate the differences by looking at examples of operators that take two operands.

29-Apr-20 Computer Science Department

24

Infix, Postfix and Prefix

Infix notation

 The operator comes between the operands  This is the usual way we write expressions X + Y .  An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer." 29-Apr-20 Computer Science Department

25

Infix, Postfix and Prefix

Infix notation

 Infix notation needs extra information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules.

29-Apr-20 Computer Science Department

26

Infix, Postfix and Prefix

Infix notation

 For example, the usual rules for associativity say that we perform operations from left to right, so the multiplication by A is assumed to come before the division by D. Similarly, the usual rules for precedence say that we perform multiplication and division before we perform addition and subtraction.

29-Apr-20 Computer Science Department

Infix, Postfix and Prefix

27 Postfix notation

    Also known as "Reverse Polish notation“ Operators are written after their operands X Y +.

The infix expression given above is equivalent to A B C + * D / The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before the multiplication.

29-Apr-20 Computer Science Department

28

Infix, Postfix and Prefix

Postfix notation

29-Apr-20  Operators act on values immediately to the left of them. For example, the "+" above uses the "B" and "C". We can add (totally unnecessary) brackets to make this explicit: ( (A (B C +) *) D /) Thus, the "*" uses the two values immediately preceding: "A", and the result of the addition. Similarly, the "/" uses the result of the multiplication and the "D".

Computer Science Department

Infix, Postfix and Prefix

29 Prefix notation

29-Apr-20    Also known as "Polish notation“ Operators are written before their operands + X Y. The expressions given above are equivalent to / * A + B C D As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two nearest values on the right. I have again added (totally unnecessary) brackets to make this clear: (/ (* A (+ B C) ) D) Computer Science Department

Infix, Postfix and Prefix

30 Prefix notation

29-Apr-20   Although Prefix "operators are evaluated left-to-right", they use values to their right, and if these values themselves involve computations then this changes the order that the operators have to be evaluated in.

In the example above, although the division is the first operator on the left, it acts on the result of the multiplication, and so the multiplication has to happen before the division (and similarly the addition has to happen before the multiplication).

Computer Science Department

Infix, Postfix and Prefix

31 Examples

Examples: 29-Apr-20

Infix

A * B + C / D

Postfix Prefix Notes

multiply A and B, A B * C D / + + * A B / C D divide C by D, add the results add B and C, A * (B + C) / D A B C + * D / / * A + B C D multiply by A, divide by D divide C by D, A * (B + C / D) A B C D / + * * A + B / C D add B, multiply by A

Converting between these notations

Computer Science Department The most straightforward method is to start by inserting all the implicit brackets that show the order of evaluation e.g.:

Infix Postfix Prefix

( (A * B) + (C / D) ) ( (A B *) (C D /) +) (+ (* A B) (/ C D) ) ((A * (B + C) ) / D) ( (A (B C +) *) D /) (/ (* A (+ B C) ) D) (A * (B + (C / D) ) ) (A (B (C D /) +) *) (* A (+ B (/ C D) ) ) You can convert directly between these bracketed forms simply by moving the operator within the brackets e.g. (X + Y) or (X Y +) or (+ X Y) . Repeat this for all the operators in an expression, and finally remove any superfluous brackets.

Examples:

32 Infix

A * B + C / D

Postfix Prefix Notes

multiply A and B, A B * C D / + + * A B / C D divide C by D, add the results add B and C, A * (B + C) / D A B C + * D / / * A + B C D multiply by A,

Infix, Postfix and Prefix

A * (B + C / D) A B C D / + * * A + B / C D divide by D divide C by D, add B, multiply by A

Examples Converting between these notations

The most straightforward method is to start by inserting all the implicit brackets that show the order of evaluation e.g.:

Infix Postfix Prefix

( (A * B) + (C / D) ) ( (A B *) (C D /) +) (+ (* A B) (/ C D) ) ((A * (B + C) ) / D) ( (A (B C +) *) D /) (/ (* A (+ B C) ) D) (A * (B + (C / D) ) ) (A (B (C D /) +) *) (* A (+ B (/ C D) ) ) You can convert directly between these bracketed forms simply by moving the operator within the brackets e.g. (X + Y) or (X Y +) or (+ X Y) . Repeat this for all the operators in an expression, and finally remove any superfluous brackets.

29-Apr-20 Computer Science Department

33

End Of Chapter

• References: Text book, chapter4: Stacks 29-Apr-20 Computer Science Department