Docsity

Stacks and Queues - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Stacks and Queues - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

7/11/

1

Stacks and Queues

Stack and Heap

• A stack is a first-in-last-out structure 7/11/

2

-^

When a method is called computer stores allrelated data in a place called stack

-^

When the method returns, stack is usedgenerate the return parameters

7/11/

4

A Stack interface

public interface Stack {

public void

push(Object x);

public void

pop();

public Object top();public boolean isEmpty();public void

clear();

7/11/

5

Stacks are LIFO

e d^ c b a

Push

operations:

Implementing Stacks

7/11/

7/11/

8

Implementing stacks using

arrays

• Use an array-based representation. •^

What are some advantages and disadvantages of anarray-based representation?

a^

b

c top

7/11/

10

Queues

•^

Behavior– add item only from the back (enqueue)– remove items only from the front (dequeue)

-^

Many Applications–

printer queue

-^

network queues

-^

common resource sharing

•^

Queue Operations– enqueue– dequeue– clear– empty– full

7/11/

11

A Queue interface

public interface Queue {

public void

enqueue(Object

x);

public Object dequeue();public boolean isEmpty();public void

clear();

7/11/

13

Queues are FIFO

front

back

k

r^

q

c^

m

Enqueue y

operation:

7/11/

14

Queues are FIFO

front

back

k

r^

q

c^

m

y

Enqueue

operation:

Implementing Queues

7/11/

Implementing a Queue with an

array

• What are the disadvantages? 7/11/

7/11/

19

A queue from two stacks

j^ i h g f

Enqueue

a b^ c d e

Dequeue

What happenswhen the stackon the rightbecomes empty?

Applications

7/11/