Part (a)
// returns a reference to the node at index k,
// where the indexes are numbered 0 through size()-1
// precondition: 0 <= k < size()
private ListNode getKthNode(int k)
{
ListNode node = front;
for (int count = 0; count < k; count++)
node = node.getNext();
return node;
}
Part (b)
// removes the last num nodes from other and attaches them
// in the same order to the end of this WaitingList;
// updates the number of nodes in each list to reflect the move
// precondition: size() > 0;
// 0 < num <= other.size()
public void transferNodesFromEnd(WaitingList other, int num)
{
ListNode tail = getKthNode(numNodes - 1);
ListNode node = other.getKthNode(other.numNodes - num);
if (other.numNodes == num)
other.front = null;
else
{
ListNode prev = other.getKthNode(other.numNodes - num - 1);
prev.setNext(null);
}
tail.setNext(node);
numNodes += num;
other.numNodes -= num;
}
|