• No results found

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

N/A
N/A
Protected

Academic year: 2021

Share "1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures"

Copied!
23
0
0

Loading.... (view fulltext now)

Full text

(1)

1.00 Lecture 35

Data Structures:

Introduction Stacks, Queues

Reading for next time: Big Java: 15.1-15.3

Data Structures

•  Set of reusable classes used in algorithms, simulations, operating systems, applications to:

–  Structure, store and manage data required by algorithms –  Optimize the access to data required by algorithms

•  There is a small number of common data structures

–  We cover the basic version of the core structures, except graphs/networks

–  Many variations exist on each structure

•  Three ways to build and use a data structure

–  Use the Java built-in version

–  Build your own class, using an array to store the data

–  Build your own class, using a linked list to store the data

(2)

Stacks

Top d Si

La q

Ap

b 1.

z 2.

3.

ngle ended structure st-in, first-out (LIFO) list

plications:

Simulation: robots, machines Recursion: pending function calls Reversal of data

Queues

e b w d u

Front Rear Double ended structure

First-in, first-out (FIFO) list Applications:

1. Simulation: lines

2. Ordered requests: device drivers, routers, 

3. Searches

(3)

Double ended Queues (Dequeues)

d a b c e

Double ended structure Applications:

1. Simulation: production, operations 1 3 3 2 3 1 2 1 3 2 2

Track 1 Track 2 Track 3

Engine Train

Engine

A dequeue can model both stacks and queues

Binary Trees

m

p e

f

d n v

Level Nodes 0 2

0

1 2

1

2 2

2



k 2

k

•  Binary tree has 2

(k+1)

-1 nodes

•  A maximum of k steps are required to find (or not find) a node E.g. 2

20

nodes, or 1,000,000 nodes, in 20 steps!

•  Binary trees can be built in many ways: search trees, heaps

•  Applications: fast storage and retrieval of data, search/sort priority queues (heaps)

•  A few algorithms use general trees (variable number of nodes):

sets (union, intersection), matrices (bases), graphics

(4)

Exercise 1

•  What data structure would you use to model:

–  People getting on and off the #1 bus at the MIT stop thru front and back doors

–  A truss in a CAD program –  A conveyor belt

–  The emergency room at a hospital –  The lines at United Airlines at Logan –  The Cambridge street network

–  Books to be reshelved at the library

Stacks

Stack s

4 = Capacity -1 3

2 1 0

Top -1

(5)

Stacks

Stack s

4 = Capacity -1 3

2 Push(a)

1

Top a 0

Top -1

Stacks

Stack s

4 = Capacity -1 3

2 Push(a)

b Push(b)

Top 1

Top a 0

Top -1

(6)

Stacks

Stack s

4 = Capacity -1 3

Top c 2 Push(a)

 Push( b) 

Top b 1

Push(c)

Top a 0

Top -1

Stacks

Stack s

4 = Capacity -1 3

Top c 2 Push(a)

  Push(b)

Top b 1

Push(c)

Top a 0

Pop() c

Top -1

(7)

Stacks

Stack s

4 = Capacity -1 3

Top c 2 Push(a)

Push(

Top b 1 b)

Push(c)

Top a 0

Pop() c

Top -1

Pop() b

S

Stack Interface

import java.util.*; // For exception

public interface Stack {

    public boolean isEmpty();

    public void push( Object o );

    public Object pop() throws EmptyStackException;

    public void clear();

}

// Interface Stack is an abstract data type // We will implement ArrayStack as a concrete // data type, to the Stack specification

// We dont use generics (<T>) here because they dont // interact cleanly with simple arrays. Code requires // ugly casts. Generic version in download.

(8)

Using a Stack to Reverse an Array

p

public class Reverse {

public static void main(String args[]) { int[] array = { 12, 13, 14, 15, 16, 17 };

Stack stack = new ArrayStack();

for (int i = 0; i < array.length; i++) { Integer y= new Integer(array[i]);

stack.push(y);

}

while (!stack.isEmpty()) {

Integer z= (Integer) stack.pop();

System.out.println(z);

} } }

// Output: 17 16 15 14 13 12

ArrayStack, 1

// Download ArrayStack; youll be writing parts of it // Download Stack and Reverse also.

import java.util.*;

public class ArrayStack implements Stack { public static final int DEFAULT_CAPACITY = 8;

private Object[] stack;

private int top = -1;

private int capacity;

public ArrayStack(int cap) { capacity = cap;

stack = new Object[capacity];

}

public ArrayStack() {

this( DEFAULT_CAPACITY );

}

(9)

E

Exercise 2: ArrayStack, 2

public boolean isEmpty() {

// Complete this method (one line) }

public void clear() {

// Complete this method (one line) }

Exercise 3: ArrayStack, 3

public void push(Object o) { // Complete this code

// If stack is full already, call grow() }

private void grow() { capacity *= 2;

Object[] oldStack = stack;

stack = new Object[capacity];

System.arraycopy(oldStack, 0, stack, 0, top+1);

}

(10)

E

Exercise 4: ArrayStack, 4

public Object pop()

throws EmptyStackException {

// Complete this code

// If stack is empty, throw exception }

// When you finish this, save/compile and run Reverse

Queues

A queue is a data structure to which you add new items at one end and remove old

items from the other.

1 2 3 4 ... n-2 n-1 n n+1

Remove items here

Add items here

(11)

Queue

Rear

Front

Queue

Rear

a

Front

(12)

Queue

Rear

a b

Front

Queue

Rear

"a" "b" "c"

Front

(13)

Queue

Rear

"b" "c"

Front

Queue

Rear Rear Rear Rear

"a" "b" "c"

Front Front

Rear

"c" "d"

Unused! Front Run out of room!

(14)

Queue

"c" "d"

Rear

Front

Wrap around!

Ring Queue

0 1

2 3 4

Capy-1

Rear Front

Front points to first element.

Rear points to

rear element.

(15)

Ring Queue

Front points to first element.

Rear points to rear element.

Capy-1

Front 0 Rear

"a"

1 4

2 3

Ring Queue

0 1

2 3 4

Capy-1

Rear Front

"b"

ont points to st element.

ar points to ar element.

"a"

Fr

fir

Re

re

(16)

Ring Queue

0 1

2 3 4

Capy-1

Rear

Front

"a"

("a" is still in slot 1 but we dont show it)

Front points to first element.

Rear points to rear element.

"b"

Ring Queue

0 1

2 3 4

Capy-1

Rear

Front "c

Front points to first element.

Rear points to rear element.

"b"

(17)

Ring Queue

0 1

2 3 4

Capy-1

Rear

Front "c" "d"

ront points to irst element.

ear points to ear element.

"b"

F f R r

Ring Queue

0 1

2 3 4

Capy-1

Rear

"d"

"b"

ront points to irst element.

ear points to ear element.

"c"

F

f

R

r

(18)

Ring Queue

0 1

2 3 4

Capy-1

Rear Front

Front

Front

"b"

"c" "d"

"a"

"a"

"b"

ront points to irst element.

ear points to ear element.

F f R r

Queue Interface

i

import java.util.*;

public interface Queue {

    public boolean isEmpty();

    public void add( Object o );

    public Object remove() throws NoSuchElementException;

    public void clear();

}

(19)

Implementing a Ring Queue

p

public class RingQueue implements Queue { private Object[] queue;

private int front;

private int rear;

private int capacity;

private int size = 0;

static public final int DEFAULT_CAPACITY= 8;

RingQueue Data Members

queue: Holds a reference to the ring array front: If size>0, holds the index to the next

item to be removed from the queue

rear: If size>0, holds the index to the last item that was added to the queue capacity: Holds the size of the array referenced

by queue

(20)

E

Exercise 5: RingQueue Methods 1

public RingQueue(int cap) { capacity = cap;

front = 0;

rear = capacity - 1;

queue= new Object[capacity];

}

public RingQueue() {

this( DEFAULT_CAPACITY );

}

public boolean isEmpty() { // Complete this method }

public void clear() { // Complete this method }

E

Exercise 6: RingQueue Methods 2

public void add(Object o) { // Complete this method // If queue full, call grow() // Add Object to rear, update size }

public Object remove() { if ( isEmpty() )

throw new NoSuchElementException();

else {

// Complete this method

// Get front object, move front index // Update size, return front object }

}

// See download code for grow() method

(21)

Java Dequeue, ArrayDeque

•  For stacks, queues and dequeues, Java has

–  interface Deque

–  class ArrayDeque implements Deque

•  For a stack use:

–  push() and pop()

•  For a queue use:

–  addLast() and removeFirst()

•  For a deque use:

–  addFirst(), addLast(), removeFirst(), removeLast()

•  For all use:

–  clear(), contains(), isEmpty(), size(), etc.

–  See javadoc for ArrayDeque, Deque

i im

Deque example: stack, queue

port java.util.*;

public class DequeExample {

public static void main(String[] args) { // Stack: use only push() and pop()

Deque<String> stack= new ArrayDeque<String>();

stack.push("Al");

stack.push("Bob");

stack.push("Claire");

stack.push("Deb");

System.out.println("Stack:");

while (!stack.isEmpty())

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

// Queue: use only addLast() and removeFirst() Deque<String> queue= new ArrayDeque<String>();

queue.addLast("Al");

queue.addLast("Bob");

queue.addLast("Claire");

queue.addLast("Deb");

System.out.println("\nQueue:");

(22)

Example output

S Stack:

Deb Claire Bob Al

Queue:

Al Bob Claire Deb

(23)

MIT OpenCourseWare http://ocw.mit.edu

1.00 / 1.001 / 1.002 Introduction to Computers and Engineering Problem Solving

Spring 2012

For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

References

Related documents

By combining the qualitative research with the quantitative interviews, secondary research, and existing inter nal information in adjacent markets, InfoTrends has compiled a

Master Repository Controller 11 network 11 ports 11 T task templates adding to favorites 24 creating/editing 24 definition 5 importing/exporting 24 list of 81 management 23 tasks

Therefore dynamic SCPC delivers the same dynamic bandwidth allocation functionality of the iDirect Shared Service, while dramatically reducing required return link

While using the same compressor and turbine wheels as in the KJ66 design, it is simpler to make and cheaper to maintain in the longer term.. The KJ66 provided a quantum leap in

Shown in cyan are the residues binding the metal cluster in L-ferritin; in orange, the iron-binding amino acids in the ferroxidase site of the cata- lytically active H-subunit and

Sofern nicht anders vermerkt, ist die Leuchte mit einem 20° Reflektor ausgestattet. Unless countermanded, the product is equipped with

Dalam hal ini perjanjian internasional yang menjadi objek kajian adalah Mutual Commitments antara Pemerintah Liberia dan United Nations Peacebuilding Commision dalam

Images and/or recordings in which I am identified will not be released and/or used without a specific written authorization from me or my legal representative unless it is for