Top Banner
1-5 Stacks Last-In-First-Out (LIFO)
23

Explantaion of Stacks and Queues_1

Nov 30, 2015

Download

Documents

nikhilteja2

After viewing this presentation you'll get the idea of how stacks and queues work.

In this presentation:

> Introduction to Stacks and Queues

> Implementation of Stacks and Queues

> Application of Stacks and Queues in Computer Science
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Explantaion of Stacks and Queues_1

1-5 Stacks

Last-In-First-Out (LIFO)

Page 2: Explantaion of Stacks and Queues_1

1 Stack ADT: Operations

2

A Stack is a collection of data that is accessed in a last-in-first-out (LIFO) manner

Major operations: “push”, “pop”, and “peek”.

stackstack

push(item)Pop()

Peek()

item

Page 3: Explantaion of Stacks and Queues_1

1 Stack ADT: Uses

3

Calling a function Before the call, the state of computation is saved on the stack so

that we will know where to resume

Recursion Matching parentheses Evaluating arithmetic expressions (e.g. a + b – c) :

postfix calculation Infix to postfix conversion

Traversing a maze

Page 4: Explantaion of Stacks and Queues_1

1 Stack: Usage

4

ec

sStack s = new Stack();

s.push (“a”);

s.push (“b”);

s.push (“c”);

d = s.peek ();

s.pop ();

s.push (“e”);

s.pop ();

d

a

b

c

Q: Can “a” be replaced by ‘a’?

A: Yes

B: No

Q: Can “a” be replaced by ‘a’?

A: Yes

B: NoTo be accurate, it is the references to “a”, “b”, “c”, …, being pushed or popped.

Page 5: Explantaion of Stacks and Queues_1

2 Stack Implementation: Array Use an Array with a top index pointer

5

F G

0 1 7 8 92 3 4 5 6

A B C D E

StackArr

arr

push(“F”);

push(“G”);

pop();

top

maxsize

10

Page 6: Explantaion of Stacks and Queues_1

3 Stack Implementation: Linked List Method #1 (Composition): Use BasicLinkedList

6

num_nodes

Top = Front of List

StackLL

list

a1 a2 a3 a4

head

BasicLinkedList

4

Page 7: Explantaion of Stacks and Queues_1

5 Application 1: Bracket Matching

7

Ensures that pairs of brackets are properly matched

An example: {a,(b+f[4])*3,d+f[5]}

Incorrect examples:

(..)..) // too many close brackets

(..(..) // too many open brackets

[..(..]..) // mismatched brackets

Page 8: Explantaion of Stacks and Queues_1

5 Application 1: Bracket Matching

8

create empty stack

for every char read

{

if open bracket then

push onto stack

if close bracket, then

pop from the stack

if doesn’t match or underflow then flag error

}

if stack is not empty then flag error

Example { a -( b + f [ 4 ] ) * 3 * d + f [ 5 ] }

Stack

{

(

[

)

}

]

[ ]

Q: What type of error does the last line test for?

A: too many closing bracketsB: too many opening bracketsC: bracket mismatch

Q: What type of error does the last line test for?

A: too many closing bracketsB: too many opening bracketsC: bracket mismatch

Page 9: Explantaion of Stacks and Queues_1

5 Application 2: Arithmetic Expression

9

Terms Expression: a = b + c * d Operands: a, b, c, d Operators: =, +, –, *, /, %

Precedence rules: Operators have priorities over one another as indicated in a table (which can be found in most books & our first few lectures) Example: * and / have higher precedence over + and –. For operators at the same precedence (such as *

and /), we process them from left to right

Page 10: Explantaion of Stacks and Queues_1

5 Application 2: Arithmetic Expression

10

Infix - operand1 operator operand2

Prefix- operator operand1 operand2

Postfix - operand1 operand2 operator

(2+3)*4

2+(3*4) 2 3 4 * +

2+3*4

infix 2 3 + 4 *

postfix

Unique interpretationAmbiguous, need ()

or precedence rules

Page 11: Explantaion of Stacks and Queues_1

5 Application 2: Arithmetic Expression

11

Algorithm: Calculating Postfix expression with stack Create an empty stack for each item of the expression, if it is an operand, push it on the stack if it is an operator, pop arguments from stack; perform the operation; push the result onto the stack

Stack

2 3 4

+

*

3 7

2

4

s.push(2)s.push(3)s.push(4)arg2 = s.pop ()arg1 = s.pop ()s.push (arg1 + arg2)arg2 = s.pop ()arg1 = s.pop ()s.push (arg1 * arg2)

2 * (3 + 4) 2 3 4 + *

arg1

arg2

4

3

7

2

14

Infix postfix

Page 12: Explantaion of Stacks and Queues_1

5 Application 2: Arithmetic Expression Brief steps for Infix to Postfix Conversion1. Scan infix expression from left to right

2. If an operand is found, add it to the postfix expression.

3. If a “(” is found, push it onto the stack.

4. If a “)” is found

a) repeatedly pop the stack and add the popped operator to the postfix expression until a “(” is found.

b) remove the “(”.

5. If an operator is found

a) repeatedly pop the operator from stack which has higher or equal precedence than/to the operator found, and add the popped operator to the postfix expression.

b) add the new operator to stack

6. If no more token in the infix expression, repeatedly pop the operator from stack and add it to the postfix expression.  

12

Page 13: Explantaion of Stacks and Queues_1

5 Application 2: Arithmetic Expression (6/7)

13

Algorithm: Converting Infix to an equivalent Postfix

ch Stack (bottom to top) postfixExpa a– – a( – ( ab – ( a b+ – ( + a bc – ( + a b c* – ( + * a b cd – ( + * a b c d) – ( + a b c d *

– ( a b c d * + – a b c d * +

/ – / a b c d * +e – / a b c d * + e

a b c d * + e / –

Move operators from stack to postfixExp until '('

Copy remaining operators from stack to postfixExp

Move operators from stack to postfixExp until '('

Copy remaining operators from stack to postfixExp

Example: a – ( b + c * d ) / eExample: a – ( b + c * d ) / e

Page 14: Explantaion of Stacks and Queues_1

6-10 Queues

First-In-First-Out (FIFO)

Page 15: Explantaion of Stacks and Queues_1

6 Queue ADT: Operations

15

A Queue is a collection of data that is accessed in a first-in-first-out (FIFO) manner

Major operations: “poll” (or “dequeue”), “offer” (or “enqueue”), and “peek”.

queuequeue

offer(item)poll()

Front of queue

Back of queue

peek()

Page 16: Explantaion of Stacks and Queues_1

6 Queue ADT: Uses

16

Print queue Simulations Breadth-first traversal of trees Checking palindromes - for illustration only as it is not a

real application of queue

Page 17: Explantaion of Stacks and Queues_1

7 Queue Implementation: Array Use an Array with front and back pointer

17

F G

0 1 7 8 92 3 4 5 6

A B C D E

QueueArr

arr

offer(“F”);

offer(“G”);

poll();

back

maxsize

10

front

Page 18: Explantaion of Stacks and Queues_1

7 Queue Implementation: Array “Circular”Array needed to recycle space

18

Given a queue

AB

C

DEF

G

0

1

7

8

9

2

3

456

To advance the indexes, use front = (front+1) % maxsize; back = (back+1) % maxsize;

C

0 1 7 8 92 3 4 5 6

A B D E F G

front

back

back

front

Page 19: Explantaion of Stacks and Queues_1

7 Queue Implementation: Array Question: what does (front == back) mean?

A: Full queue

B: Empty queue

C: Both A and B

D: Neither A nor B

19

Page 20: Explantaion of Stacks and Queues_1

7 Queue Implementation: Array Ambiguous full/empty state

20

QueueFullState

size 0 size 4

Solution 1 – Maintain queue size or full status

e f c dQueueEmptyState

FB

FB

Solution 2 (Preferred and used in our codes) – Leave a gap!

Don’t need the size field this way

Full Case: (((B+1) % maxsize) == F)Empty Case: F == B

e c d

B F

Page 21: Explantaion of Stacks and Queues_1

8 Queue Implementation: Linked List Method #1 (Composition): Use TailedLinkedList

Do not use BasicLinkedList as we would like to use addLast() of TailedLinkedList.

21

num_nodes

QueueLL

list

a1 a2 a3 a4

head

TailedLinkedList

4tail

Page 22: Explantaion of Stacks and Queues_1

8 Queue Implementation: Linked List Method #2 (Inheritance): Extend TailedLinkedList

For your information only. Inheritance is not covered by CS1020

22

num_nodes

a1 a2 a3 a4

head

4tail

QueueLLE TailedLinkedList

Page 23: Explantaion of Stacks and Queues_1

10 Application: Palindromes

23

A string which reads the same either left to right, or right to left is known as a palindrome Palindromes: “radar”, “deed”, “aibohphobia” Non-palindromes: “data”, “little”

“c1 c2 c3 c4 c5”

< c5, c4, c3, c2, c1 >

< c1, c2, c3, c4, c5 >

AlgorithmGiven a string, use:

a Stack to reverse its ordera Queue to preserve its order

Check if the sequences are the same

top

front

input

tail

stack

Queue