Write a class that maintains the top ten scores for a game application, implemen
ID: 669916 • Letter: W
Question
Write a class that maintains the top ten scores for a game application, implementing the add and remove methods of Section 3.1.1, but using a singly linked list instead of an array.
public void add(GameEntry e) { 11 int newScore = e.getScore( ); 12 // is the new entry e really a high score? 13 if (numEntries < board.length || newScore > board[numEntries1].getScore( )) { 14 if (numEntries < board.length) // no score drops from the board 15 numEntries++; // so overall number increases 16 // shift any lower scores rightward to make room for the new entry 17 int j = numEntries 1; 18 while (j > 0 && board[j1].getScore( ) < newScore) { 19 board[j] = board[j1]; // shift entry from j-1 to j 20 j; // and decrement j 21 } 22 board[j] = e; // when done, add new entry 23 } 24 }
public GameEntry remove(int i) throws IndexOutOfBoundsException { 27 if (i < 0 || i >= numEntries) 28 throw new IndexOutOfBoundsException("Invalid index: " + i); 29 GameEntry temp = board[i]; // save the object to be removed 30 for (int j = i; j < numEntries 1; j++) // count up from i (not down) 31 board[j] = board[j+1]; // move one cell to the left 32 board[numEntries 1 ] = null; // null out the old last score 33 numEntries; 34 return temp; // return the removed object 35 }
Explanation / Answer
add and remove methods using a singly linked list:
public SLinkedList<GameEntry> add(GameEntry rank, SLinkedList<GameEntry> scores)
{
Node<GameEntry> currentNode = scores.getFirst();
Node<GameEntry> nextNode = null;
Node<GameEntry> previousNode = null;
Node<GameEntry> newNode = new Node<GameEntry>();
newNode.setElement(rank);
if(scores.getSize() == 0)
{
scores.addFirst(newNode);
}
else
{
while(currentNode != null)
{
nextNode = currentNode.getNext();
if(nextNode == null)
{
scores.addLast(newNode);
}
else
{
scores.addAfter(currentNode, newNode);
break;
}
previousNode = currentNode;
currentNode = currentNode.getNext();
}
}
return scores;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.