You are on page 1of 24

Chapter 9: Linear Data Structures

Solutions
Multiple Choice
Solutions
1. c
2. e
3. a
4. e
5. b
6. b
7. d
8. a
9. c
10. e

True/False
Solutions
1. T
2. T
3. F
4. T
5. F
6. T
7. T
8. F
9. T
10. F

Short Answer Solutions


9.1.

Suppose current is a reference to a ListNode object and that it currently refers to a specific node in a linked
list. Show, in pseudocode, the steps that would delete the node following current from the list. Keep in
mind that current can refer to the first and last nodes in the list.
// assumes each node has a reference field called next
// assumes next refers to a subsequent node if there is one
if current.next is not null then
current.next = current.next.next;
endIf

9.2.

Modify your answer to the previous exercise assuming that the list was set up as a doubly linked list, with both
next and prev references.
if current.next is not null then
if current.next.next is not null then
current.next.next.prev = current;
endIf
current.next = current.next.next;
endIf

9.3.

Suppose current and newNode are references to ListNode objects. Assume current currently refers
to a specific node in a linked list and newNode refers to an unattached ListNode object. Show, in
pseudocode, the steps that would insert newNode behind current in the list. Keep in mind that current can
refer to the first and last nodes in the list.
// assumes each node has a reference field called next
// assumes next refers to a subsequent node if there is one
newNode.next = current.next;
current.next = newNode;

9.4.

Modify your answer to the previous problem assuming that the list was set up as a doubly linked list, with both
next and prev references.

2007 Pearson Education

S 218

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

S 219

newNode.prev = current;
if current.next is null then
newNode.next = null;
else
newNode.next = current.next;
current.next.prev = newNode;
endIf
current.next = newNode;

9.5.

Would the front and rear references in the header node of a linked list ever refer to the same node? Would they
ever both be null? Would one ever be null if the other was not? Explain your answers using examples.
The front and rear references in the header node of a linked list would refer to
the same node if the list consists of only a single node. They would both be null
if the list were empty. One would never be null if the other were not. For
example, if the linked list consisted on a single node containing the string
William and a null next reference (since there is no successor node), both the
front and rear references would contain reference this node. If the node
containing William were deleted, both the front and rear references would be set
to null. It is impossible to have a list which has a front, but no rear or a rear
but no front, making it impossible for one reference to be null and the other not.

9.6.

Show the contents of a queue after the following operations are performed. Assume the queue is initially
empty.
enqueue (45);
45
enqueue (12);
12 45
enqueue (28);
28 12 45
dequeue();
28 12
dequeue();
28
enqueue (69);
69 28
enqueue (27);
27 69 28
enqueue (99);
99 27 69 28
dequeue();
99 27 69
enqueue (24);
24 99 27 69
enqueue (85);
85 24 99 27 69
enqueue (16);
16 85 24 99 27 69
dequeue();
16 85 24 99 27

9.7.

In terms of the final state of a queue, does it matter how dequeue operations are intermixed with enqueue
operations? Does it matter how the enqueue operations are intermixed among themselves? Explain using
examples.
In terms of the final state of a queue, as long as the number of dequeue opertions
does not exceed the number of enqueue operations, the intermixing of these
operations does not matter. It does matter how the enqueue operations are
intermixed among themselves; an item which arrives earlier moves closer to the
front of the quene than an item which arrives later.
As an example of intermixing enqueue and dequeue operations, consider enqueuing
six integers such as 2, 3, 5, 7, 11, and 13 and then dequeuing half of them. The
resulting queue contains 7, 11, and 13. Alternatively, suppose that the same six
integers are enqueued, but every time two integers are enqueued, one is dequeued.
The resulting queue contains 7, 11, and 13. This does not prove than the

2007 Pearson Education

S 220

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

intermixing of dequeue and enqueue operations is inconsequential; it merely shows


that it is inconsequential in this case. On the other hand if the enqueue
operations are intermixed among themselves, such as enqueuing the 13 first and the
2 last (instead of 2 first and 13 last), the resulting queue would contain 7, 11,
and 2 (instead of 7, 11, and 13). This single case is sufficient to prove that
the intermixing of enqueue operations matters.

9.8.

Show the contents of a priority queue after the following operations are performed. Assume the queue starts
out empty. For the enqueue operation, the first parameter is the element and the second parameter is its priority
so that (45, 5) means element 45 has a priority of 5. Assume that the smaller the number the higher the
priority.
enqueue (45, 5);
45
enqueue (12, 8);
45 12
enqueue (28, 2);
28 45 12
dequeue();
45 12
dequeue();
12
enqueue (69, 0);
69 12
enqueue (27, 6);
69 27 12
enqueue (99, 9);
69 27 12 99
dequeue();
27 12 99
enqueue (24, 4);
24 27 12 99
enqueue (85, 2);
85 24 27 12 99
enqueue (16, 3);
85 16 24 27 12 99
dequeue();
16 24 27 12 99

9.9.

Show the contents of a stack after the following operations are performed. Assume the stack is initially empty.
push (45);
45
push (12);
45 12
push (28);
45 12 28
pop();
45 12
pop();
45
push (69);
45 69
push (27);
45 69 27
push (99);
45 69 27 99
pop();
45 69 27
push (24);
45 69 27 24
push (85);
45 69 27 24 85
push (16);
45 69 27 24 85 16
pop();
45 69 27 24 85

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

9.10.

S 221

In terms of the final state of a stack, does it matter how the pop operations are intermixed with the push
operations? Does it matter how the push operations are intermixed among themselves? Explain using
examples.
In terms of the final state of a stack, the number of pop operations must not
exceed the number of push operations, and the intermixing of pop and push
operations matters. How the push operations are intermixed among themselves also
matters.
For example, suppose the six integers 2, 3, 5, 7, 11, and 13 are pushed onto a
stack, and then three integers are popped off the stack. The resulting stack
contains 2, 3, and 5. Alternatively, suppose that the same six integers are
pushed onto the stack, put every time 2 integers are pushed onto the stack, one is
popped. The resulting stack contains 2, 5, and 11. This single illustration is
sufficient to prove that the intermixing of push and pop operations matters.
Similarly, if the 13 is pushed onto the stack first and the 2 is pushed onto the
stack last (instead of the 2 first and the 13 last), with no popping, the 2 is at
the top of the stack and the 13 is at the bottom of the stack (instead of the 2 at
the bottom and the 13 at the top). Again, this single example is sufficient to
prove that the intermixing of push operations among themselves matters.

9.11.

Two methods of searching were presented in Chapter 6: sequential search and binary search. If we have sorted
data stored in a linked list, which searching method would be most efficient? Explain.
Sequential (aka linear) search would be most efficient because a linked list is by
nature a sequential data structure and it does not provide random access. When the
data are sorted, a binary search may be used, and this involves jumping to the
middle of the list, or to the middle of a section of the list. There is no way to
do that directly with a linked list. The middle can only be accessed by iterating
sequentially through the list, following links, until the middle element is
reached. So a binary search would be more inefficient than a sequential search in
this case.

Programming Project Solutions


9.1 CD
//********************************************************************
// CD.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.1
//
// Represents a compact disc.
//********************************************************************
import java.text.NumberFormat;
public class CD
{
private String title, artist;
private double cost;
private int tracks;
//----------------------------------------------------------------// Creates a new CD with the specified information.
//----------------------------------------------------------------public CD (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
//---------------------------------------------------------------- 2007 Pearson Education

S 222

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

// Returns a description of this CD.


//----------------------------------------------------------------public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}
9.1 CDCollection
//********************************************************************
// CDCollection.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.1
//
// Represents a collection of compact discs. Implemented using a
// linked list.
//********************************************************************
import java.text.NumberFormat;
import java.util.LinkedList;
public class CDCollection
{
private CDNode collection;
private double totalCost;
private int count;
//----------------------------------------------------------------// Creates an initially empty collection.
//----------------------------------------------------------------public CDCollection ()
{
collection = null;
totalCost = 0.0;
count = 0;
}
//----------------------------------------------------------------// Adds a CD to the collection.
//----------------------------------------------------------------public void addCD (String title, String artist, double cost,
int tracks)
{
CDNode node = new CDNode (new CD (title, artist, cost, tracks));
CDNode current;
if (collection == null)
collection = node;
else
{
current = collection;
while (current.next != null)
current = current.next;
current.next = node;
}
totalCost += cost;
count++;
}
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

//----------------------------------------------------------------// Returns a report describing the CD collection.


//----------------------------------------------------------------public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nCD List:\n\n";
CDNode current = collection;
if (current != null)
{
report += current.cd.toString() + "\n";
while (current.next != null)
{
current = current.next;
report += current.cd.toString() + "\n";
}
}
return report;
}
//*****************************************************************
// An inner class that represents a node in the CD list.
// The public variables are accessed by the CDCollection class.
//*****************************************************************
private class CDNode
{
public CD cd;
public CDNode next;
//-------------------------------------------------------------// Sets up the node
//-------------------------------------------------------------public CDNode (CD current)
{
cd = current;
next = null;
}
}
}
9.1 Tunes
//********************************************************************
// Tunes.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.1
//
// Driver for demonstrating the use of a linked list of objects.
//********************************************************************
public class Tunes
{
//----------------------------------------------------------------// Creates a CDCollection object and adds some CDs to it. Prints
// reports on the status of the collection.
//----------------------------------------------------------------public static void main (String[] args)
2007 Pearson Education

S 223

S 224

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

{
CDCollection music = new CDCollection ();
music.addCD
music.addCD
music.addCD
music.addCD

("Storm Front", "Billy Joel", 14.95, 10);


("Come On Over", "Shania Twain", 14.95, 16);
("Soundtrack", "Les Miserables", 17.95, 33);
("Graceland", "Paul Simon", 13.90, 11);

System.out.println (music);
music.addCD ("Double Live", "Garth Brooks", 19.99, 26);
music.addCD ("Greatest Hits", "Jimmy Buffet", 15.95, 13);
System.out.println (music);
}
}
9.2 Magazine
//********************************************************************
// Magazine.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.2
//
// Represents a single magazine.
//********************************************************************
public class Magazine implements Comparable
{
private String title;
//----------------------------------------------------------------// Sets up the new magazine with its title.
//----------------------------------------------------------------public Magazine (String newTitle)
{
title = newTitle;
}
//----------------------------------------------------------------// Returns this magazine as a string.
//----------------------------------------------------------------public String toString ()
{
return title;
}
//----------------------------------------------------------------// Implementation of the Comparable class method
//----------------------------------------------------------------public int compareTo(Object obj)
{
Magazine other = (Magazine)obj;
return title.compareTo(other.title);
}
}
9.2 MagazineList
//*******************************************************************
// MagazineList.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.2
//
// Represents a collection of magazines.
//*******************************************************************
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

public class MagazineList


{
private MagazineNode list;
//---------------------------------------------------------------// Sets up an initially empty list of magazines.
//---------------------------------------------------------------public MagazineList()
{
list = null;
}
//---------------------------------------------------------------// Creates a new MagazineNode object and inserts it in lexicographical
// order relative to the other nodes in the linked list. If
// magazine already in list, do not insert.
//---------------------------------------------------------------public void insert (Magazine mag)
{
MagazineNode node = new MagazineNode (mag);
MagazineNode current;
MagazineNode previous = null;
boolean done = false;
if (list == null)
list = node;
else
{
current = list;
while (!done)
{
int compareResult = current.magazine.compareTo(mag);
if (compareResult == 0) // duplicate
return;
if (compareResult > 0) // add before current
{
if (previous != null)
previous.next = node;
else
list = node;
node.next = current;
done = true;
}
else
if (current.next == null) // add after current
{
current.next = node;
done = true;
}
else // move to next
{
previous = current;
current = current.next;
}
}
}
}
//---------------------------------------------------------------// If the Magazine mag is in the list, removes it from
// the linked list. Returns true if the deletion was
// successful, false otherwise.
//--------------------------------------------------------------- 2007 Pearson Education

S 225

S 226

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

public boolean delete (Magazine mag)


{
MagazineNode current = list;
MagazineNode previous = null;
if (current == null)
return false;
while (current.next != null)
{
if (current.magazine.compareTo(mag) == 0) // match
{
if (previous != null)
previous.next = current.next;
else
list = current.next;
return true;
}
previous = current;
current = current.next;
}
return false;
}
//---------------------------------------------------------------// Returns this list of magazines as a string.
//---------------------------------------------------------------public String toString ()
{
String result = "";
MagazineNode current = list;
while (current != null)
{
result += current.magazine + "\n";
current = current.next;
}
return result;
}
//*****************************************************************
// An inner class that represents a node in the magazine list.
// The public variables are accessed by the MagazineList class.
//*****************************************************************
private class MagazineNode
{
public Magazine magazine;
public MagazineNode next;
//-------------------------------------------------------------// Sets up the node
//-------------------------------------------------------------public MagazineNode (Magazine mag)
{
magazine = mag;
next = null;
}
}
}
9.2 MagazineRack
//*******************************************************************
// MagazineRack.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.2
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

S 227

//
// Driver to exercise the MagazineList collection.
//*******************************************************************
public class MagazineRack
{
//---------------------------------------------------------------// Creates a MagazineList object, inserts and deletess several magazines to
the
// list, then prints it.
//---------------------------------------------------------------public static void main (String[] args)
{
MagazineList rack = new MagazineList();
rack.insert (new Magazine("Time"));
rack.insert (new Magazine("Woodworking Today"));
rack.insert (new Magazine("Communications of the ACM"));
rack.insert (new Magazine("House and Garden"));
rack.insert (new Magazine("GQ"));
rack.delete (new Magazine("House and Garden"));
rack.delete (new Magazine("Communications of the ACM"));
rack.insert (new Magazine("Woodworking Today"));
rack.insert (new Magazine("Fine Cooking"));
rack.delete (new Magazine("Not in list"));
System.out.println (rack);
}
}
9.3 SelectionSort
//********************************************************************
// SelectionSort.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.3
//
// Demonstrates the selection sort using a linked list
//********************************************************************
public class SelectionSort {
private SortNode list;
//----------------------------------------------------------------// Creates an initially empty linked list.
//----------------------------------------------------------------public SelectionSort()
{
list = null;
}
//----------------------------------------------------------------// Adds an integer to the linked list
//----------------------------------------------------------------public void add(int value)
{
SortNode node = new SortNode(value);
SortNode current = null;
if (list == null)
list = node;
else
{
current = list;
while (current.next != null)
current = current.next;
current.next = node;
}
2007 Pearson Education

S 228

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

}
//----------------------------------------------------------------// Sorts the linked list using the selection sort.
//----------------------------------------------------------------public void sort()
{
SortNode current = list;
SortNode min = list;
SortNode swapPos = list;
if (list == null)
return;
while (swapPos.next != null)
{
while (current.next != null) // find min value
{
current = current.next;
if (current.value < min.value)
min = current;
}
// Swap the values
if (min != swapPos) // a swap was found
{
int temp = min.value;
min.value = swapPos.value;
swapPos.value = temp;
}
swapPos = swapPos.next;
current = swapPos;
min = current;
}
}
//----------------------------------------------------------------// Returns a listing of the contents of the linked list.
//----------------------------------------------------------------public String toString()
{
String report = "";
SortNode current = list;
if (current != null)
{
report += String.valueOf(current.value) + " ";
while (current.next != null)
{
current = current.next;
report += String.valueOf(current.value) + " ";
}
}
return report;
}
//*****************************************************************
// An inner class that represents a node containing an integer.
//*****************************************************************
private class SortNode
{
public int value;
public SortNode next;
//-------------------------------------------------------------// Sets up the node
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

//-------------------------------------------------------------public SortNode (int current)


{
value = current;
next = null;
}
}
}
9.3 SelectionSortDriver
//********************************************************************
// SelectionSortDriver.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.3
//
// Driver for demonstrating the selection sort on a linked list of int's.
//********************************************************************
import java.util.Random;
public class SelectionSortDriver {
static final int MAX_NUMBERS = 25;
static final int MAX_INT_VALUE = 100;
public static void main (String args[])
{
Random g = new Random();
SelectionSort sort = new SelectionSort();
int numInts = g.nextInt(MAX_NUMBERS);
System.out.println("Sorting " + numInts + " integers");
for (int i=0; i<numInts; i++)
sort.add(g.nextInt(MAX_INT_VALUE));
System.out.println(sort);
sort.sort();
System.out.println("Sorted:");
System.out.println(sort);
}
}
9.4 InsertionSort
//********************************************************************
// InsertionSort.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.4
//
// Demonstrates the insertion sort using a linked list
//********************************************************************
public class InsertionSort {
private SortNode list;
//----------------------------------------------------------------// Creates an initially empty linked list.
//----------------------------------------------------------------public InsertionSort()
{
list = null;
}
2007 Pearson Education

S 229

S 230

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

//----------------------------------------------------------------// Adds an integer to the linked list


//----------------------------------------------------------------public void add(int value)
{
SortNode node = new SortNode(value);
SortNode current = null;
if (list == null)
list = node;
else
{
current = list;
while (current.next != null)
current = current.next;
current.next = node;
}
}
//---------------------------------------------------------------// Inserts SortNode in list in ascending order relative
// to the other nodes in list.
//---------------------------------------------------------------private void insert (SortNode node)
{
SortNode current;
SortNode previous = null;
boolean done = false;
if (list == null)
list = node;
else
{
current = list;
while (!done)
{
if (current.value > node.value) // add before current
{
if (previous != null)
previous.next = node;
else
list = node;
node.next = current;
done = true;
}
else
if (current.next == null) // add after current
{
current.next = node;
done = true;
}
else // move to next
{
previous = current;
current = current.next;
}
}
}
}
//----------------------------------------------------------------// Sorts the linked list using the insertion sort.
//----------------------------------------------------------------public void sort()
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

SortNode current = list;


list = null;
if (current == null)
return;
// add first node
SortNode temp = current;
current = current.next;
temp.next = null;
insert(temp);
// add suceeding nodes
while (current != null)
{
temp = current;
current = current.next;
temp.next = null;
insert(temp);
}
}
//----------------------------------------------------------------// Returns a listing of the contents of the linked list.
//----------------------------------------------------------------public String toString()
{
String report = "";
SortNode current = list;
if (current != null)
{
report += String.valueOf(current.value) + " ";
while (current.next != null)
{
current = current.next;
report += String.valueOf(current.value) + " ";
}
}
return report;
}
//*****************************************************************
// An inner class that represents a node containing an integer.
//*****************************************************************
private class SortNode
{
public int value;
public SortNode next;
//-------------------------------------------------------------// Sets up the node
//-------------------------------------------------------------public SortNode (int current)
{
value = current;
next = null;
}
}
}

9.4 InsertionSortDriver
//********************************************************************
// InsertionSortDriver.java
Author: Lewis/Loftus/Cocking
2007 Pearson Education

S 231

S 232

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

//
// Solution to Programming Project 9.4
//
// Driver for demonstrating the insertion sort on a linked list of int's.
//********************************************************************
import java.util.Random;
public class InsertionSortDriver {
static final int MAX_NUMBERS = 25;
static final int MAX_INT_VALUE = 100;
public static void main (String args[])
{
Random g = new Random();
InsertionSort sort = new InsertionSort();
int numInts = g.nextInt(MAX_NUMBERS);
System.out.println("Sorting " + numInts + " integers");
for (int i=0; i<numInts; i++)
sort.add(g.nextInt(MAX_INT_VALUE));
System.out.println(sort);
sort.sort();
System.out.println("Sorted:");
System.out.println(sort);
}
}
9.5 TicketSimulation
//*******************************************************************
//
// Solution to Programming Project 9.5
//
// Simulates customers waiting in line at a movie theater to buy
// tickets using a queue.
//*******************************************************************
import java.util.Random;
public class TicketSimulation {
private Random gen;
private int custCount;
private Line line;
private final int MAX_NUM_CUSTOMERS = 5;
private final int MAX_CUST_SERVICED = 4;
public TicketSimulation()
{
gen = new Random();
custCount = 0;
line = new Line();
}
//---------------------------------------------------------------// Runs the simulation for specified number of cycles. After the
// cycles are over, the ticket window closes.
//---------------------------------------------------------------public void run(int cycles)
{
int numCust, custServiced;
Customer person;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

S 233

for (int i=0; i<cycles; i++)


{
numCust = gen.nextInt(MAX_NUM_CUSTOMERS); // customers arrive
for (int j=0; j<numCust; j++)
{
person = new Customer(custCount++);
line.addCustomer(person);
System.out.println(person + " joins the line");
}
custServiced = gen.nextInt(MAX_CUST_SERVICED); // customers serviced
for (int j=0; j<custServiced; j++)
{
if (line.isEmpty())
System.out.println("Waiting");
else
{
System.out.println(line.nextCustomer() + " is being
serviced");
}
}
}
System.out.println("Ticket counter closing . . .");
while (!line.isEmpty())
System.out.println(line.nextCustomer() + " is being serviced");
}
public static void main (String args[])
{
new TicketSimulation().run(10);
}
}
9.5 Line
//*******************************************************************
// Line.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.5 & 9.6
//
// A queue class used to represent a line of customers
//*******************************************************************
import java.util.LinkedList;
import java.util.Queue;
public class Line {
Queue<Customer> queue;
//---------------------------------------------------------------// Creates a new line based on a queue
//---------------------------------------------------------------public Line()
{
queue = new LinkedList<Customer>();
}
//---------------------------------------------------------------// Removes a customer from the head of the queue
//---------------------------------------------------------------public Customer nextCustomer()
{
2007 Pearson Education

S 234

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

return queue.remove();
}
//---------------------------------------------------------------// Adds a customer to the tail of the queue
//---------------------------------------------------------------public void addCustomer(Customer person)
{
queue.add(person);
}
//---------------------------------------------------------------// Indicates whether the queue is empty
//---------------------------------------------------------------public boolean isEmpty()
{
return queue.isEmpty();
}
//---------------------------------------------------------------// Returns the number of customers in the queue
//---------------------------------------------------------------public int size()
{
return queue.size();
}
}
9.5 Customer
//*******************************************************************
// Customer.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.5 & 9.6
//
// Encapsulates a customer
//*******************************************************************
public class Customer {
int id;
//---------------------------------------------------------------// Creates a customer with ID = number
//---------------------------------------------------------------public Customer(int number)
{
id = number;
}
public String toString()
{
return "Customer " + id;
}
}
9.6 Ticket4Simulation
//*******************************************************************
// Ticket4Simulation.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.6
//
// Simulates customers waiting in four lines at a movie theater
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

S 235

// to buy tickets using a queue data structure.


//*******************************************************************
import java.util.Random;
import java.text.DecimalFormat;
public class Ticket4Simulation {
private Random gen;
private int custCount;
private Line[] lines;
private int tellers[];
private int stats[];
private final int MAX_NUM_CUSTOMERS = 20;
private final int MAX_CUST_SERVICED = 5;
private final int NUM_TELLERS = 4;
public Ticket4Simulation()
{
gen = new Random();
custCount = 0;
lines = new Line[NUM_TELLERS];
stats = new int[NUM_TELLERS];
for (int i = 0; i<NUM_TELLERS; i++)
{
lines[i] = new Line();
stats[i] = 0;
}
tellers = new int[NUM_TELLERS];
}
//---------------------------------------------------------------// Displays the stats for each teller, and identifies the teller
// with the shortest waiting time on average.
//---------------------------------------------------------------private void displayStats(int numCycles)
{
float max = 0f;
float average;
int best = 0;
DecimalFormat form = new DecimalFormat("#0.0");
System.out.println("\nAverage customers served per cycle:\n
number");

Teller

for (int i=0; i<NUM_TELLERS; i++)


System.out.print(" " + i + " ");
System.out.println("\n-----------------------------------------");
for (int i=0; i<NUM_TELLERS; i++)
{
System.out.print(" ");
average = (float)stats[i] / numCycles;
if (average > max)
{
max = average;
best = i;
}
System.out.print(form.format(average) + " ");
}
System.out.println("\n\nTeller " + best + " had shortest average waiting
time");
2007 Pearson Education

S 236

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

}
//---------------------------------------------------------------// Finds the shortest line at the bank and adds person to that
// line. Returns the line number;
//---------------------------------------------------------------private int findShortestLine(Customer person)
{
int lineNumber = 0;
int leastCustomers = lines[0].size();
for (int i=1; i<NUM_TELLERS; i++)
{
if (lines[i].size() < leastCustomers)
{
lineNumber = i;
leastCustomers = lines[i].size();
}
}
lines[lineNumber].addCustomer(person);
return lineNumber;
}
//---------------------------------------------------------------// Runs the simulation for specified number of cycles. After the
// cycles are over, the bank closes.
//---------------------------------------------------------------public void run(int cycles)
{
int numCust, custServiced;
int tellerTime;
int lineJoined;
int max;
Customer person;
for (int i=0; i<cycles; i++)
{
numCust = gen.nextInt(MAX_NUM_CUSTOMERS); // customers arriving
for (int j=0; j<numCust; j++)
{
person = new Customer(custCount++);
System.out.println(person + " joins line " +
findShortestLine(person));
}
max = 0;
for (int j=0; j<NUM_TELLERS; j++)
{
custServiced = gen.nextInt(MAX_CUST_SERVICED); // customers
served
if (custServiced > max)
max = custServiced;
tellers[j] = custServiced;
if (custServiced <= lines[j].size())
stats[j] += custServiced;
else
stats[j] += lines[j].size();
}
for (int j=0; j<max; j++)
{
for (int k = 0; k < NUM_TELLERS; k++)
{
if (tellers[k]-- > 0)
if (lines[k].isEmpty())
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

System.out.println("Teller " +

S 237

k + " waiting for

new customers");
else
System.out.println("Teller " + k + " finished
serving " + lines[k].nextCustomer());
}
}
}
System.out.println("Ticket window closing . . .");
for (int i=0; i<NUM_TELLERS; i++)
while (!lines[i].isEmpty())
System.out.println("Teller " + i + " is serving " +
lines[i].nextCustomer());
displayStats(cycles);
}
public static void main (String args[])
{
new Ticket4Simulation().run(10);
}
}
9.6 Line
//*******************************************************************
// Line.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.5 & 9.6
//
// A queue class used to represent a line of customers
//*******************************************************************
import java.util.LinkedList;
import java.util.Queue;
public class Line {
Queue<Customer> queue;
//---------------------------------------------------------------// Creates a new line based on a queue
//---------------------------------------------------------------public Line()
{
queue = new LinkedList<Customer>();
}
//---------------------------------------------------------------// Removes a customer from the head of the queue
//---------------------------------------------------------------public Customer nextCustomer()
{
return queue.remove();
}
//---------------------------------------------------------------// Adds a customer to the tail of the queue
//---------------------------------------------------------------public void addCustomer(Customer person)
{
queue.add(person);
}
//--------------------------------------------------------------- 2007 Pearson Education

S 238

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

// Indicates whether the queue is empty


//---------------------------------------------------------------public boolean isEmpty()
{
return queue.isEmpty();
}
//---------------------------------------------------------------// Returns the number of customers in the queue
//---------------------------------------------------------------public int size()
{
return queue.size();
}
}
9.6 Customer
//*******************************************************************
// Customer.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.5 & 9.6
//
// Encapsulates a customer
//*******************************************************************
public class Customer {
int id;
//---------------------------------------------------------------// Creates a customer with ID = number
//---------------------------------------------------------------public Customer(int number)
{
id = number;
}
public String toString()
{
return "Customer " + id;
}
}

9.7PostfixEvaluator
//*******************************************************************
// PostfixEvaluator.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 9.7
//
// Evaluates a postfix expression that operates on integer operands
// using the arithmetic operators +, -, *, /, and %. Inputs is
// assumed to be in valid postfix form.
//*******************************************************************
import java.util.Stack;
import java.util.StringTokenizer;
public class PostfixEvaluator {
//---------------------------------------------------------------// Parses the string and returns the int value. If the string is
// invalid, return -1.
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

S 239

//---------------------------------------------------------------private static int getIntValue(String s)


{
int result = -1;
try
{
result = Integer.parseInt(s);
}
catch (NumberFormatException e)
{}
return result;
}
//---------------------------------------------------------------// Evaluates the postfix expression and returns the result
//---------------------------------------------------------------public static float evaluate(String expression)
{
Stack stack = new Stack();
StringTokenizer parser = new StringTokenizer(expression);
String token;
int tokenIntValue;
float firstOperator, secondOperator;
while (parser.hasMoreTokens())
{
token = parser.nextToken();
char firstChar = token.charAt(0);
if (Character.isDigit(firstChar) ||
// token is a positive or
negative number
(token.length() > 1 && firstChar == '-'))
stack.push(new Float(getIntValue(token)));
else
{
secondOperator = ((Float)stack.pop()).floatValue();
firstOperator = ((Float)stack.pop()).floatValue();
switch (firstChar)
{
case '+' :
stack.push(new
break;
case '-' :
stack.push(new
break;
case '*' :
stack.push(new
break;
case '/' :
stack.push(new
break;
case '%' :
stack.push(new
break;
}

Float(firstOperator + secondOperator));
Float(firstOperator - secondOperator));
Float(firstOperator * secondOperator));
Float(firstOperator / secondOperator));
Float(firstOperator % secondOperator));

}
}
return ((Float)stack.pop()).floatValue();
}
//--------------------------------------------------------------- 2007 Pearson Education

S 240

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

// main method, used for testing the static


// method PostfixEvaluator.evaluate(). Can be
// removed when testing complete.
//---------------------------------------------------------------public static void main (String args[])
{
String expression = " 5 2 + 8 5 - *";
System.out.println(expression);
System.out.println("Result : " + PostfixEvaluator.evaluate(expression));
expression = "2 4 - 5 2 * +";
System.out.println(expression);
System.out.println("Result : " + PostfixEvaluator.evaluate(expression));
expression = "9 3 / 6 / 4 * 10 -";
System.out.println(expression);
System.out.println("Result : " + PostfixEvaluator.evaluate(expression));
expression = "9 3 / 6 / 4 * 10 - 3 /";
System.out.println(expression);
System.out.println("Result : " + PostfixEvaluator.evaluate(expression));
}
}
AP-Style Multiple Choice
Solutions
1. B
2. B
3. D
4. A
5. A
6. D

AP-Style Free Response Solution


9.1
a.
public int size ()
{
int len = 0;
DoubleListNode cur = head;
while (cur != null)
{
cur = cur.getNext();
len++;
}
return len;
}

b.
public void addBack (Object val)
{
DoubleListNode newNode = new DoubleListNode(val, null, tail);
if (head == null)

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 9 Solutions

{
head = newNode;
tail = newNode;
}
else
{
tail.setNext(newNode);
tail = newNode;
}
}

c.
public void insertTwo (Object val1, Object val2, int index)
{
if (index == 0)
{
addFront(val2);
addFront(val1);
}
else if (index == size())
{
addBack(val1);
addBack(val2);
}
else
{
DoubleListNode n1 = new DoubleListNode(val1, null, null);
DoubleListNode n2 = new DoubleListNode(val2, null, n1);
n1.setNext(n2);
DoubleListNode cur = head;
for (int i=1; i < index; i++)
{
cur = cur.getNext();
}
cur.getNext().setPrev(n2);
n2.setNext(cur.getNext());
cur.setNext(n1);
n1.setPrev(cur);
}
}

2007 Pearson Education

S 241

You might also like