Transcript
Page 1: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

CMPT 225Stacks and Queues

Page 2: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Outline

Abstract Data Types Stacks Queues Priority Queues

September 2004 John Edgar 2

Page 3: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Postfix

September 2004 John Edgar 3

Page 4: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Reverse Polish Notation

Reverse Polish Notation (RPN) Also known as postfix notation A mathematical notation

▪ Where every operator follows its operands Invented by Jan Łukasiewicz in 1920

Example Infix: 1 + 2 RPN: 1 2 +

September 2004 John Edgar 4

Page 5: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Reverse Polish Notation

More interesting example Infix: 5 + ((1 + 2) * 4) − 3 RPN: 5 1 2 + 4 * + 3 –

Cleaner, no backets

September 2004 John Edgar 5

Page 6: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

RPN Example

5 1 2 + 4 * + 3 –

September 2004 John Edgar 6

5

store 5 store 1 store 2

Apply + to the last two operands

1

2

Page 7: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

RPN Example

5 1 2 + 4 * + 3 –

September 2004 John Edgar 7

5

store 5 store 1 store 2

Apply + to the last two operands

store result store 4

Apply * to the last two operands

3

4

Page 8: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

RPN Example

5 1 2 + 4 * + 3 –

September 2004 John Edgar 8

5

store 5 store 1 store 2

Apply + to the last two operands

store result store 4

Apply * to the last two operands

store result12

Apply + to the last two operands

Page 9: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

RPN Example

5 1 2 + 4 * + 3 –

September 2004 John Edgar 9

store 5 store 1 store 2

Apply + to the last two operands

store result store 4

Apply * to the last two operands

store result

store 3

Apply + to the last two operands

store result

3

Apply - to the last two operands

17

Page 10: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

RPN Example

5 1 2 + 4 * + 3 –

September 2004 John Edgar 10

store 5 store 1 store 2

Apply + to the last two operands

store result store 4

Apply * to the last two operands

store result

store 3

Apply + to the last two operands

store result

Apply - to the last two operands

14

store result

retrieve answer

Page 11: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Data Structure

What are the storage properties of the data structure that we used? Specifically how are items inserted and

removed? The last item to be entered is the first item to

be removed Known as LIFO (Last In First Out)

A stack

September 2004 John Edgar 11

Page 12: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack

September 2004 John Edgar 12

Page 13: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stacks

A stack only allows items to be inserted and removed at one end We call this end the top of the stack The other end is called the bottom

Access to other items in the stack is not allowed

September 2004 John Edgar 13

Page 14: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Postfix and Stacks

A stack can be used to naturally store data for postfix notation Operands are stored at the top of the stack And removed from the top of the stack

Notice that we have not (yet) discussed how a stack should be implemented Just what it does

An example of an Abstract Data Type

September 2004 John Edgar 14

Page 15: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Abstract Data Types

September 2004 John Edgar 15

Page 16: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Abstract Data Types

A collection of data Describes the data but not how it is stored

Set of operations on the data Describes precisely what effect the operations

have on the data but Does not specify how operations are carried

out An ADT is not a data structure

September 2004 John Edgar 16

Page 17: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Concrete Data Type

The term concrete data type is usually used in contrast with an ADT

An ADT is a collection of data and a set of operations on the data

A concrete data type is an implementation of an ADT using a data structure A construct that is defined in a programming

language to store a collection of data

September 2004 John Edgar 17

Page 18: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

ADT Operators

Mutators Accessors Other

September 2004 John Edgar 18

Page 19: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Mutators

Often known as setters Operations that change the contents of an

ADT, usually subdivided into▪ Adding data to a data collection and▪ Removing data from a collection

Different ADTs allow data to be added and removed at different locations

September 2004 John Edgar 19

Page 20: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Accessors

Often known as getters Retrieve data from the collection

e.g. the item at the top of the stack Ask questions about the data collection

Is it full? How many items are stored? …

September 2004 John Edgar 20

Page 21: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

What Not How

Information related to storage implementation should be hidden

An ADT’s operations can be used in the design of other modules or applications Other modules do not need to know the

implementation of the ADT operations Allowing the implementation of operations to

be changed without affecting other modules

September 2004 John Edgar 21

Page 22: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Specification of ADT Operations

Operations should be specified in detail without discussing implementation issues

In C++ an ADT class can be divided into header (.h) and implementation (.cpp) files▪ More in later lectures

September 2004 John Edgar 22

Page 23: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack ImplementationArrays

September 2004 John Edgar 23

Page 24: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack Operations

A stack should implement at least the first two of these operations: push – insert an item at the top of the stack pop – remove and return the top item peek – return the top item

These operations are straightforward so should be performed efficiently

September 2004 John Edgar 24

Page 25: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

A Design Note

Assume that we plan on using a stack to contain integers with these methods void push (int) int pop()

We can design other modules that use these methods Without having to know anything about how

they, or the stack itself, are implemented

September 2004 John Edgar 25

Page 26: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Classes

We will use classes to encapsulate stacks Encapsulate – enclose in

A class is a programming construct that contains Data for the class Operations of the class More about classes later …

September 2004 John Edgar 26

Page 27: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack Implementation

The stack ADT can be implemented using a variety of data structures, e.g. Arrays Linked Lists

Both implementations must implement all the stack operations And in constant time (time that is independent

of the number of items in the stack)

September 2004 John Edgar 27

Page 28: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Implementation

Let’s use an array to implement a stack We will need to keep track of the index

that represents the top of the stack When we insert an item increment this index

When we delete an item decrement this index

September 2004 John Edgar 28

Page 29: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Stack Example

September 2004 John Edgar 29

0 1 2 3 4 5

index of top is current size – 1

//Java CodeStack st = new Stack();

Page 30: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Stack Example

September 2004 John Edgar 30

60 1 2 3 4 5

index of top is current size – 1

//Java CodeStack st = new Stack();st.push(6); //top = 0

Page 31: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Stack Example

September 2004 John Edgar 31

6 1 7 80 1 2 3 4 5

index of top is current size – 1

//Java CodeStack st = new Stack();st.push(6); //top = 0st.push(1); //top = 1 st.push(7); //top = 2 st.push(8); //top = 3

Page 32: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Stack Example

September 2004 John Edgar 32

6 1 70 1 2 3 4 5

index of top is current size – 1

//Java CodeStack st = new Stack();st.push(6); //top = 0st.push(1); //top = 1 st.push(7); //top = 2 st.push(8); //top = 3 st.pop(); //top = 2

Page 33: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Stack Example

Java coding example

September 2004 John Edgar 33

Page 34: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Implementation Summary

Easy to implement a stack with an array And push and pop can be performed in

constant time But what happens when the array is full? Once the array is full

No new values can be inserted or A new, larger, array has to be created

▪ And the existing items copied to this new array

September 2004 John Edgar 34

Page 35: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Digression

September 2004 John Edgar 35

Page 36: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Arrays

Arrays contain identically typed values These values are stored sequentially in main

memory Values are stored at specific numbered

positions in the array called indexes The first value is stored at index 0, the second

at index 1, the ith at index i-1, and so on The last item is stored at position n-1,

assuming that n values are stored in the array

September 2004 John Edgar 36

Page 37: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Indexing

int[] arr = {3,7,6,8,1,7,2}; Creates an integer array with 7 elements

To access an element refer to the array name and the element's index int x = arr[3]; assigns the value of

the fourth array element (8) to x arr[5] = 11; changes the sixth

element of the array from 7 to 11 arr[7] = 3; results in an error because

the index is out of bounds

September 2004 John Edgar 37

index

value

0 3

1 7

2 6

3 8

4 1

5 7

6 2

11

In Java this results in an ArrayIndexOutOfBoundsException

Page 38: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Indexing

C++ coding example

September 2004 John Edgar 38

Page 39: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Arrays and Main Memory

September 2004 John Edgar 39

int[] grade; Declares an array variable

grade

In Java arrays are objects, so this is a reference variable

This symbol represents the “null pointer”

main memory is depicted below this line

Note: Java syntax. C++ is int * grade;

Page 40: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Arrays and Main Memory

0

0

0

0

September 2004 John Edgar 40

int[] grade;

grade = new int[4]; Creates a new array of size 4

grade

main memory is depicted below this line

Stores 4 ints consecutively. The ints are initialized to 0

refers to the newly created array object

Page 41: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Arrays and Main Memory

0

0

0

0

September 2004 John Edgar 41

int[] grade;

grade = new int[4];

grade[2] = 23;Assigns 23 to the third item in the array

grade

main memory is depicted below this line

But how does the system “know” where grade[2] is?

23

Page 42: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Memory Addresses

Access to array elements is very fast An array variable references the array

A reference is just a main memory address The address is stored as number, with each

address referring to one byte of memory▪ Address 0 would be the first byte▪ Address 1 would be the second byte▪ Address 20786 would be the twenty thousand,

seven hundred and eighty seventh byte▪ …

September 2004 John Edgar 42

Page 43: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Offset Calculations

Consider grade[2] = 23; How do we find this element in the array?

Consider what we know The address of the first array element The type of the values stored in the array

▪ And therefore the size of the array elements The index of the element to be accessed

We can calculate the address of the element to be accessed address of first element + (index * type size)

September 2004 John Edgar 43

Page 44: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Offset Example

1280 1290

1281 1291

1282 1292

1283 1293

1284 1294

1285 1295

1286 1296

1287 1297

1288 1298

1289 1299

September 2004 John Edgar 44

The int stored at grade[2] is located at byte:

1282 + 2 * 4 =

1290

grade

Stores a reference to the start of the array, in this case byte 1282

Page 45: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Passing Arrays to Methods

Array variables are reference variables An array variable argument to a method

passes the address of the array▪ And not the elements of the array

Changes made to the array by a method are made to the original array object If this is not desired, a copy of the array

should be made within the method

September 2004 John Edgar 45

Page 46: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Positions

What if array positions carry meaning? An array that is sorted by name, or grade or

some other value Or an array where the position corresponds to

a position of some entity in the world The ordering should be maintained as

elements are inserted or removed

September 2004 John Edgar 46

Page 47: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Insertion and Removal into Ordered Arrays

When an item is inserted either Write over the element at the given index or Move the element, and all elements after it,

up one position When an item is removed either

Leave gaps in the array, i.e. array elements that don't represent values or

Move all the values after the removed value down one index

September 2004 John Edgar 47

Page 48: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Arrays are Static

The size of an array must be specified when it is created And cannot then be changed

If the array is full values can’t be inserted There are, time consuming, ways around this To avoid this problem we can make arrays

much larger than they are needed However this wastes space

September 2004 John Edgar 48

Page 49: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Summary

Good things about arrays Fast, random access, of elements using a

simple offset calculation Very memory efficient, as little memory is

required other than the data itself Easy to use

Bad things about arrays Slow deletion and insertion of elements for

ordered arrays Size must be known when the array is created

September 2004 John Edgar 49

Page 50: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked List Digression

September 2004 John Edgar 50

Page 51: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

A Dream Data Structure

It would be nice to have a data structure that is Dynamic Does fast insertions/deletions in the middle

We can achieve this using linked lists …

September 2004 John Edgar 51

Page 52: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked Lists

A linked list is a dynamic data structure that consists of nodes linked together

A node is a data structure that contains data the location of the next node

September 2004 John Edgar 52

7

Page 53: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked Lists

A linked list is a chain of nodes where each node stores the address of the next node

September 2004 John Edgar 53

6 2

7

start

8

This symbol indicates a null

reference

Page 54: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked Lists

September 2004 John Edgar 54

7

// Javaclass Node { public int data; public Node next;}

// C++class Node { public: int data;

Node *next;};

Page 55: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked Lists// Javaclass Node { public int data; public Node next;}

// C++class Node { public: int data;

Node *next;};

September 2004 John Edgar 55

7

A node points to another node, so the reference must be of

type Node

Page 56: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Building a Linked List

Node a = new Node(7, null);

September 2004 John Edgar 56

a

Assume we’ve added a constructor to the Node

class that lets us initialize data and next

like this.

7

// C++Node *a = new Node(7, null);

Page 57: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Building a Linked List

Node a = new Node(7, null);a.next = new Node(3, null);

57

a

7 3

a.nexta->next

a.dataa->data

a.next.dataa->next->data

// C++Node *a = new Node(7, null);a->next = new Node(3, null);

Page 58: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Traversing a Linked List

Node a = new Node(7, null);a.next = new Node(3, null);Node p = a;

58

a

7 3

p

// C++Node *a = new Node(7, null);a->next = new Node(3, null);Node *p = a;

Page 59: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Traversing a Linked List

Node a = new Node(7, null);a.next = new Node(3, null);Node p = a;p = p.next; // go to the next node

September 2004 John Edgar 59

a

7 3

We can walk through a linked list by going from node to node.

p Node *a = new Node(7, null);a->next = new Node(3, null);Node *p = a;p = p->next;// go to the next node

Page 60: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Traversing a Linked List

Node a = new Node(7, null);a.next = new Node(3, null);Node p = a;p = p.next; // go to the next nodep = p.next;

September 2004 John Edgar 60

a

7 3

Eventually, p reaches the end of the list and becomes null.

p Node *a = new Node(7, null);a->next = new Node(3, null);Node *p = a;p = p->next; // go to the next nodep = p->next;

Page 61: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Encapsulating Linked Lists

The previous example showed a list built out of nodes

In practice a linked list is encapsulated in its own class Allowing new nodes to be easily inserted and

removed as desired The linked list class has a pointer to the (node

at the) head of the list Implementations of linked lists vary

September 2004 John Edgar 61

Page 62: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack ImplementationLinked Lists

September 2004 John Edgar 62

Page 63: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Stack: Linked List

Nodes should be inserted and removed at the head of the list New nodes are pushed onto the front of the

list, so that they become the top of the stack Nodes are popped from the front of the list

Straight-forward linked list implementation Both push and pop affect the front of the list

▪ There is therefore no need for either algorithm to traverse the entire list

September 2004 John Edgar 63

Page 64: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked List Implementation

September 2004 John Edgar 64

public void push(int x){// Make a new node whose next reference is// the existing list

Node newNode = new Node(x, head);head = newNode; //head points to new node

}

public int pop(){// Return the value at the head of the list

int temp = head.data;head = head.next;return temp; //head points to new node

}// Garbage collection deallocates old head

Java

Page 65: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked List Implementation

September 2004 John Edgar 65

void LinkedList::push(int x){// Make a new node whose next reference is// the existing list

Node *newNode = new Node(x, head);head = newNode; //head points to new node

}

int LinkedList::pop(){// Return the value at the head of the list

int temp = head->data;Node *ht = head;head = head->next;delete ht;return temp; //head points to new node

}

C++

Page 66: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 66

C++ CodeStack st;st.push(6);

top

6

Page 67: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 67

Java CodeStack st = new Stack();st.push(6); st.push(1);

top

6

1

Page 68: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 68

C++ CodeStack st;st.push(6); st.push(1); st.push(7);top

6

1

7

Page 69: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 69

C++ CodeStack st;st.push(6); st.push(1); st.push(7); st.push(8);

top

6

1

7

8

Page 70: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 70

Java CodeStack st = new Stack();st.push(6); st.push(1); st.push(7); st.push(8); st.pop();

top

6

1

7

8

Page 71: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Stack Example

September 2004 John Edgar 71

Java CodeStack st = new Stack();st.push(6); st.push(1); st.push(7); st.push(8); st.pop();

top

6

1

7

Page 72: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

The Call Stack

September 2004 John Edgar 72

Page 73: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Functions

Programs typically involve more than one function call A main function Which calls other functions as required

Each function requires space in main memory for its variables and parameters This space must be allocated and de-allocated

in some organized way

Page 74: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Organizing Function Calls

Most programming languages use a call stack to implement function calling When a method is called, its line number and

other data are pushed onto the call stack When a method terminates, it is popped from

the call stack Execution restarts at the indicated line number

in the method currently at the top of the stack

September 2004 John Edgar 74

Page 75: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

The Call Stack

September 2004 John Edgar 75

This is a display of the call stack (from the Eclipse Debug window)

Top of the stack: most recently called method.

Bottom of the stack: least recently called method

Page 76: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Call Stack and Memory

When a function is called space is allocated for it on the call stack This space is allocated sequentially

Once a function has run the space it used on the call stack is de-allocated Allowing it to be re-used

Execution returns to the previous function Which is now at the top of the call stack

Page 77: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Call Stack Example (Java)

public double biggerArea(double side, double r){double sq;double circ;sq = squareArea(side);circ = circleArea(r);if (sq > circ)

return sq;else

return circ;}

public double squareArea(double side){return square(side)

}

public double circleArea(double r){return Math.PI * square(r);

}

public double square(double x){return x * x;

}

public double square(double x){return x * x;

}

Page 78: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Call Stack Example (C/C++)

double biggerArea(double side, double r){double sq;double circ;sq = squareArea(side);circ = circleArea(r);if (sq > circ)

return sq;else

return circ;}

double squareArea(double side){return square(side)

}

double circleArea(double r){return 3.14 * square(r);

}

double square(double x){return x * x;

}

double square(double x){return x * x;

}

Page 79: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Call Stack Example

biggerArea(4, 2)// executing biggerArea sq = squareArea(side)// executing squareAreareturn square(side)// return to biggerArea

side r sq circbiggerArea

4 2

sidesquareArea

4

xsquare

4

16

stack

Page 80: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Call Stack Example

biggerArea(4, 2)// executing biggerArea sq = squareArea(side)// executing squareAreareturn square(side)// return to biggerAreacirc = circleArea(r)// executing circleAreareturn pi * square(r)// return to biggerAreaif (sq > circ)return sq

side r sq circbiggerArea

4 2 16

rcircleArea

2

xsquare

2

12.5…

stack

Page 81: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Returning Values

In the example, functions returned values assigned to variables in other functions They did not affect the amount of memory

required by previously called functions That is, functions below them on the call stack

Stack memory is sequentially allocated It is not possible to increase memory assigned

to a function previously pushed onto the stack

Page 82: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

What About Arrays?

Let's say we want to call a function to insert some values in an existing array If the calling function has made an array with

of the right size this is not a problem▪ The new values are stored in the existing array

But the calling function might not know how many values are to be inserted

Page 83: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Make Room

Memory on the call stack is allocated sequentially So we can’t change the size of a variable

belonging to a function already on the stack Suggesting that we can’t change the size of

an array when the program is running Either make an array large enough so that it

doesn’t overflow Or use dynamic memory

Page 84: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Dynamic Memory

What happens if we want to allocate memory at run time? It can’t be allocated to stack memory so will

need to be put somewhere else Let’s call somewhere else the heap

We still need stack variables that refer or point to the dynamically allocated memory Which we will call reference or pointer

variables

Page 85: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Variables in Dynamic Memory

Create a variable to store an address A reference of pointer variable Addresses have a fixed size If there is initially no address assign it a

special value (null) Create new data in the heap when

needed This may be done at run time

Assign the address of the data to variable This does involve more administration

Page 86: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Dynamic Memory Example// in function, f …

// Java code

int arr[];

arr = getOrdArray(5);

// …

… arrf

… null

ngetOrdArray

5

stack

int[] getOrdArray(int n){int arr[] = new int[n];for (int i = 0; i < n; ++i){

arr[i] = i * 2 + 1;}return arr;

}

heap

1 3 5 7 9

arr

Page 87: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Dynamic Memory Example// in function, f …

// C++ code

int *arr;

arr = getOrdArray(5);

// …

… arrf

… null

ngetOrdArray

5

stack

int * getOrdArray(int n){int *arr = new int[n];for (int i = 0; i < n; ++i){

arr[i] = i * 2 + 1;}return arr;

}

heap

1 3 5 7 9

arr

Page 88: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Releasing Dynamic Memory

When a function call is complete its stack memory is released and can be re-used

Dynamic memory should also be released Failing to do so results in a memory leak

It is not as easy to determine when dynamic memory should be released Data might be referred to by more than one

address variable▪ Memory should only be released when it is no

longer required by any variable

Page 89: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Dynamic vs Static

When should a data object be created in dynamic memory? When the object is required to change size, or If it is not known if the object will be required

Languages have different approaches to using static and dynamic memory In Java this is determined by the data type In C++ the programmer can choose whether

to assign data to static or dynamic memory

Page 90: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Queues

September 2004 John Edgar 90

Page 91: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Print Queues

Assume that we want to store data for a print queue for a student printer Student ID Time File name

The printer is to be assigned to file in the order in which they are received A fair algorithm

September 2004 John Edgar 91

Page 92: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Classes for Print Queues

To maintain the print queue we would require at least two classes Request class Collection class to store requests

The collection class should support the desired behaviour FIFO (First In First Out) The ADT is a queue

September 2004 John Edgar 92

Page 93: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Queues

In a queue items are inserted at the back and removed from the front As an aside queue is just the British (i.e.

correct) word for a line (or line-up) Queues are FIFO (First In First Out) data

structures – fair data structures

September 2004 John Edgar 93

Page 94: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

What Can You Use a Queue For?

Server requests Instant messaging servers queue up incoming

messages Database requests

Print queues Operating systems often use queues to

schedule CPU jobs Various algorithm implementations

September 2004 John Edgar 94

Page 95: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Queue Operations

A queue should implement at least the first two of these operations: insert – insert item at the back of the queue remove – remove an item from the front peek – return the item at the front of the

queue without removing it Like stacks, it is assumed that these

operations will be implemented efficiently That is, in constant time

September 2004 John Edgar 95

Page 96: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Queue ImplementationArrays

September 2004 John Edgar 96

Page 97: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Implementation

Consider using an array as the underlying structure for a queue, we could Make the back of the queue the current size of

the array, much like the stack implementation Initially make the front of the queue index 0 Inserting an item is easy

September 2004 John Edgar 97

0 1 2 3 4 5 6 7

4

0 1 2 3 4 5 6 7

back = 0back = 1back = 2 4 18

0 1 2 3 4 5 6 7

front = 0

Page 98: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Implementation

What happens when items are removed? Either move all remaining items down – slow Or increment the front index – wastes space

September 2004 John Edgar 98

4 18 25 2 5

0 1 2 3 4 5 6 7back = 5front = 0

18 25 2 5

0 1 2 3 4 5 6 7back = 4front = 0

4 18 25 2 5

0 1 2 3 4 5 6 7back = 5front = 1

Page 99: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Circular Arrays

Neat trick: use a circular array to insert and remove items from a queue in constant time

The idea of a circular array is that the end of the array “wraps around” to the start of the array

0 1 2 3 4 5 6 7

September 2004 John Edgar 99

0

1

3

2

4

5

6

7

Page 100: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

The mod Operator

The mod operator (%) calculates remainders: 1%5 = 1, 2%5 = 2, 5%5 = 0, 8%5 = 3

The mod operator can be used to calculate the front and back positions in a circular array Thereby avoiding comparisons to the array size The back of the queue is:

▪ (front + num) % queue.length▪ where num is the number of items in the queue

After removing an item the front of the queue is:▪ (front + 1) % queue.length;

September 2004 John Edgar 100

Page 101: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Queue Example

September 2004 John Edgar 101

0 1 2 3 4 5

//C++ CodeQueue q;q.insert(6);

6

front 0

insert item at (front + num) % queue.length

num 01

Page 102: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Queue Example

September 2004 John Edgar 102

0 1 2 3 4 5

//Java CodeQueue q = new Queue();q.insert(6);q.insert(4);q.insert(7);q.insert(3);q.insert(8);

6

front 0

4 7 3 8

num 12345

insert item at (front + num) % queue.length

Page 103: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Queue Example

September 2004 John Edgar 103

0 1 2 3 4 5

// C++ CodeQueue q;q.insert(6); q.insert(4);q.insert(7);q.insert(3);q.insert(8);q.remove();//front to 1q.remove();//front to 2q.insert(9);

6

front 0

4

make front = (0 + 1) % 6 = 1

1

7 3 8 9

num 5434

make front = (1 + 1) % 6 = 2

2

Page 104: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Array Queue Example

September 2004 John Edgar 104

0 1 2 3 4 5

//Java CodeQueue q = new Queue();q.insert(6);q.insert(4);q.insert(7);q.insert(3);q.insert(8);q.remove();//front to 1q.remove();//front to 2q.insert(9);q.insert(5);

front 2

7 3 8 95

insert at (front + num) % 6 = (2 + 4) % 6 = 0

num 45

Page 105: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Queue ImplementationLinked Lists

September 2004 John Edgar 105

Page 106: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Linked List Implementation

Removing items from the front of the queue is straightforward

Items should be inserted at the back of the queue in constant time So we would like to avoid traversing through

the list Use a second node reference to keep track of

the node at the back of the queue▪ Requires a little extra administration

September 2004 John Edgar 106

Page 107: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Queue Example

September 2004 John Edgar 107

front

6

back

// C++ CodeQueue q;q.insert(6);

Page 108: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Queue Example

September 2004 John Edgar 108

front 4

6

back

//Java CodeQueue q = new Queue();q.insert(6);q.insert(4);

Page 109: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Queue Example

September 2004 John Edgar 109

front 4

6

back

// C++ CodeQueue q;q.insert(6);q.insert(4);q.insert(7);

7

Page 110: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Queue Example

September 2004 John Edgar 110

front 4

6

back

//Java CodeQueue q = new Queue();q.insert(6);q.insert(4);q.insert(7);q.insert(3);

7

3

Page 111: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

List Queue Example

September 2004 John Edgar 111

front 4

6

back

//Java CodeQueue q = new Queue();q.insert(6);q.insert(4);q.insert(7);q.insert(3);q.remove();7

3

Page 112: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Priority Queues

September 2004 John Edgar 112

6

5

4

32

1

Page 113: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Priority Queues

Items in a priority queue are given a priority value Which could be numerical or something else

The highest priority item is removed first Uses include

System requests Data structure to support Dijkstra’s Algorithm

September 2004 John Edgar 113

Page 114: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Priority Queue Problem

Can items be inserted and removed efficiently from a priority queue? Using an array, or Using a linked list?

Note that items are not removed based on the order in which they are inserted

September 2004 John Edgar 114

Page 115: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Summary

September 2004 John Edgar 115

Page 116: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Summary

Abstract Data Types (ADTs) Specify data and operations

▪ But not how they are stored nor how they are done▪ Allow usage without knowing all the details

Examples: Stacks and Queues▪ Array-based implementations▪ Linked list-based implementations

September 2004 John Edgar 116

Page 117: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Summary

Linked lists Chain of Node data structures

▪ Each Node contains data and reference to next Node

Can be used to store an a priori unknown amount of data▪ Allocate Nodes one at a time

Efficient insertion/deletion Some overhead vs. array

September 2004 John Edgar 117

Page 118: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Summary

Memory Arrays stored as contiguous block of memory

▪ Fast access via offset calculations Static memory (stack memory) versus

dynamic memory (heap memory)▪ Variable in stack memory is gone after a function /

method call is complete▪ Variable in heap memory sticks around

September 2004 John Edgar 118

Page 119: Stacks and Queues.  Abstract Data Types  Stacks  Queues  Priority Queues September 2004John Edgar2

Readings

Carrano Ch. 3, 4, 6, 7

September 2004 John Edgar 119


Top Related