Professional Documents
Culture Documents
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
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.
S 218
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
S 220
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
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.
S 222
S 223
S 224
{
CDCollection music = new CDCollection ();
music.addCD
music.addCD
music.addCD
music.addCD
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
S 225
S 226
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
}
//----------------------------------------------------------------// 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
S 229
S 230
9.4 InsertionSortDriver
//********************************************************************
// InsertionSortDriver.java
Author: Lewis/Loftus/Cocking
2007 Pearson Education
S 231
S 232
//
// 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
S 233
S 234
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
S 235
Teller
S 236
}
//---------------------------------------------------------------// 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
System.out.println("Teller " +
S 237
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
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
S 239
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
b.
public void addBack (Object val)
{
DoubleListNode newNode = new DoubleListNode(val, null, tail);
if (head == null)
{
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);
}
}
S 241