Download Chapter 4

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Array data structure wikipedia , lookup

Transcript
COP3538 – Data
Structures Using
OOP
Chapter 4 – Stacks and
Queues
Abstract Data Structures

An array is a concrete structure
 The
Java language defines
Structure
 Rules for storing and retrieving values
 Limitations

 Uses

of an array are limitless
Limited only by the programmers imagination
 Sometimes

we require better-defined structures
Abstract data structures
Improve the structure
 Additional storage and retrieval rules
 Additional limitations

1/20/2014
Jim Littleton - COP3538
2
Abstract Data Structures

Abstract data structures
 Commonly implemented using arrays
 Can be implemented using other structures

Abstract data structure examples
 Stacks
 Queues
 Priority queues

Each abstract data structure
 Solves a particular set of problems
 Has a unique set of advantages and
1/20/2014
Jim Littleton - COP3538
disadvantages
3
Access (interface)

Arrays
 Directly
accessed via an index (immediate)
 Search through values sequentially or logically
 Only one item can be accessed at a time

Abstract data structures
 An

interface controls access to the values
Direct access is NOT possible by user (programmer)
 Implementation


1/20/2014
of the interface controls
Access to values
How values are stored, retrieved and deleted
Jim Littleton - COP3538
4
Stacks

Stack properties
 Access
to only one item at a time
 Follows the Last In First Out (LIFO) logical process

Think of any natural “stack” of items



 Four




1/20/2014
Stack of dishes
Stack of coins
Stack of papers
basic operations (know these!)
Push – place an item on top of the stack
Pop – remove an item off the top of the stack
Overflow – procedure to follow when the stack is full
Underflow – procedure to follow when the stack is empty
Jim Littleton - COP3538
5
Stacks

Code example
pubic class
private
private
private
Stack {
int maxSize;
int top = -1;
int[] array;
public Stack(int size) {
maxSize = size;
array = new int[maxSize];
}
public int pop() {
return array[top--]; // Returns the topmost item
}
public void push(int item) {
array[++top] = item; // Places item on top of the stack
}
public boolean isEmpty() { // Underflow operation
return top == -1; // Test if stack is empty
}
public boolean isFull() { // Overflow operation
return top == maxSize – 1; // Test if stack is full
}
}
1/20/2014
Jim Littleton - COP3538
6
Stacks

Important notes
 Always

Avoids ArrayIndexOutOfBounds exception
 Always


call isEmpty() before calling pop()
call isFull() before calling push()
Avoids ArrayIndexOutOfBounds exception
Extremely useful in programming
 Following
a sequence that requires backtracking
 Evaluating parenthesized expressions

1/20/2014
Arithmetical expressions
Jim Littleton - COP3538
7
Stacks

Example use of a stack
 Reverse the letters of
 Non-stack example
a word
private class NonStackApp {
public static void main(String[] args) {
String s = “COP3538”;
char[] c = new char[s.length()];
for(int x = 0; x < c.length; x++) {
c[x] = s.charAt(x);
}
for(int x = c.length – 1; x >= 0; x--) {
System.out.print(c[x]);
}
}
}
1/20/2014
Jim Littleton - COP3538
8
Stacks

Example use of a stack
 Reverse the letters
 Stack example
of a word
private class StackApp {
public static void main(String[] args) {
Stack stack = new Stack();
String s = “COP3538”;
for(int x = 0; x < s.length(); x++) {
stack.push(s.charAt(x));
}
while(!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
}
1/20/2014
Jim Littleton - COP3538
9
Stacks

A stack is a very useful data structure
 Don’t
have to keep track of array indices
 Limited access to the elements in the array


Elements are accessible only via the push and pop methods
Stack efficiency
 Push

A constant value. Why??


1/20/2014
and pop take O(1) time
Not dependent on the number of items in the stack
No comparisons or swaps necessary
Jim Littleton - COP3538
10
Queues

A First In First Out (FIFO) data Structure
 Remember:

A Stack is a LIFO data structure
Can be implemented using several structures
 Array
 Linked-list
 Etc.

Very useful for many different applications
 Print
queues
 Job queues
 Ready queues
 Keyboard queues
1/20/2014
Jim Littleton - COP3538
11
Queues

Queue Terminology (Know the terms!!)

Front


Rear


Attempting to add an element to a full queue
Underflow

1/20/2014
Inserts and removals can occur on either end
Overflow


The front and rear pointers can wrap around the queue
Deques (double-ended queue)


Front pointer always exists before the rear pointer
Circular queue


Points to the last element in the queue
Linear queue


Points to the first element in the queue
Attempting to remove an element from an empty queue
Jim Littleton - COP3538
12
Queues

Queue methods
 Insert()

Method used to store data at the rear of the queue
 Remove()

Method used to retrieve data from the front of the queue
 IsEmpty()

Tests whether the queue is empty

The queue is considered empty if the front and rear are together
 IsFull()

Tests whether the queue is full

1/20/2014
The queue is considered full if the rear equals the size of the queue
 Not necessarily true for Circular queues
Jim Littleton - COP3538
13
Linear Queue
public class LinearQueue {
private int maxSize, front, rear, numElems;
private int[] array;
public boolean isFull() {
return numElems == maxSize;
}
public Queue(int size) {
maxSize = size;
array = new int[maxSize];
front = numElems = 0;
rear = -1;
}
public int remove() {
numElems--;
return array[front++];
}
public void insert(int value) {
array[++rear] = value;
numElems++;
}
public int size() {
return numElems;
}
}
public boolean isEmpty() {
return numElems == 0;
}
1/20/2014
Jim Littleton - COP3538
14
Circular Queue
public class CircularQueue {
private int maxSize, front, rear, numElems;
private int[] array;
public boolean isFull() {
return numElems == maxSize;
}
public Queue(int size) {
maxSize = size;
array = new int[maxSize];
front = numElems = 0;
rear = -1;
}
public int remove() {
if(front == maxSize) {
front = 0; // Wrap around
}
numElems--;
return array[front++];
}
public void insert(int value) {
if(rear == maxSize - 1) {
rear = -1; // Wrap around
}
array[++rear] = value;
numElems++;
}
public int size() {
return numElems;
}
}
public boolean isEmpty() {
return numElems == 0;
}
1/20/2014
Jim Littleton - COP3538
15
Queues

Queue efficiency
 Insert()

and remove() occur in O(1) time
Simply insert or remove at front and rear pointers

Minor adjustment of front and rear values
 Even in the case when the pointers wrap the queue (circular queue)


1/20/2014
Not dependent on the number of items in the array
No comparisons or swaps necessary
Jim Littleton - COP3538
16
Priority Queue

A priority queue (pQueue)
 Similar


to a regular queue
Insert in rear (becomes inconsequential)
Remove from front
 Significant

Items are organized by a key field




The position of existing items in the queue may change
Insertion time is slower for a pQueue compared to a regular queue
Remove time is the same for both queue types
If the queue is full

1/20/2014
i.e., Last name, N#, etc.
New items are inserted in their correct positions


differences
An existing item must be removed before a new item is added
Jim Littleton - COP3538
17
Priority Queue

Several useful applications
 Scheduling
queues
Shortest job first
 Fewest resources first

 Print
queues
Fewest pages first
 Jobs sent to faster printers first


A pQueue is no longer a FIFO queue!
 The
1/20/2014
FO item is based on the specified priority
Jim Littleton - COP3538
18
Priority Queue

pQueue Code
public class PriorityQueue {
private int maxSize;
private int numElems = 0;
private int[] array;
public boolean isEmpty() {
return numElems == 0;
}
public boolean isFull() {
return numElems == maxSize;
}
public PriorityQueue(int size) {
maxSize = size;
array = new int[maxSize];
}
public void insert(int item) {
int x;
public int remove() {
return array[--numElems];
}
}
if(numElems == 0) {
array[numElems++] = item;
}
else {
x = numElems;
while(x > 0 && item > array[x - 1]) {
array[x] = array[x - 1];
x--;
}
array[x] = item;
numElems++;
}
}
1/20/2014
Jim Littleton - COP3538
This block of code is identical
to the code that performs the
copies in the Insertion Sort!
19
Priority Queue

pQueue Efficiency
 Remove
occurs at O(1) time (immediate)
 Insert occurs at O(n) time

Items have to be copied to new locations

1/20/2014
To make room for the item being inserted
Jim Littleton - COP3538
20
Questions
1/20/2014
Jim Littleton - COP3538
21