In: Computer Science
B has to be matched with A so please I need both in Java.
the previous project mean A
A. Write a class that maintains the top ten scores for a game application, implementing the add and remove methods but using a singly linked list instead of an array.
B. Perform the previous project, but use a doubly linked list. Moreover, your implementation of remove(i) should make the fewest number of pointer hops to get to the game entry at index i.
/***************** ScoreSingly.java *****************/
public class ScoreSingly {
Score head;
Score tail;
class Score {
int data;
Score next;
Score(int data) {
this.data =
data;
this.next =
null;
}
}
ScoreSingle() {
head = null;
tail = null;
}
public void add(int data) {
Score newScore = new
Score(data);
if (head == null) {
head =
newScore;
tail =
newScore;
} else {
tail.next =
newScore;
tail =
newScore;
}
}
void remove(int position) {
if (head == null)
return;
Score temp = head;
if (position == 0) {
head =
temp.next;
return;
}
for (int i = 0; temp != null
&& i < position - 1; i++)
temp =
temp.next;
if (temp == null || temp.next ==
null)
return;
Score next = temp.next.next;
temp.next = next;
}
public void display() {
Score current = head;
if (head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of singly
linked list: ");
while (current != null) {
System.out.print(current.data + " ");
current =
current.next;
}
System.out.println();
}
}
/*************** ScoreDoubly.java *************/
public class ScoreDoubly {
int ncount;
Score head;
Score tail;
class Score {
int item;
Score previous;
Score next;
public Score(int item) {
this.item =
item;
}
}
ScoreDouble() {
ncount = 0;
head = null;
tail = null;
}
public void add(int item) {
Score newScore = new
Score(item);
if (head == null) {
head = tail =
newScore;
head.previous =
null;
tail.next =
null;
} else {
tail.next =
newScore;
newScore.previous = tail;
tail =
newScore;
tail.next =
null;
}
ncount++;
}
void remove(int position) {
if (head == null) {
return;
}
if (ncount - position >
position) {
Score temp =
head;
if (position ==
0) {
head = temp.next;
ncount--;
return;
}
for (int i = 0;
temp != null && i < position - 1; i++) {
temp = temp.next;
}
if (temp == null
|| temp.next == null)
return;
Score next =
temp.next.next;
temp.next =
next;
ncount--;
} else {
if (position ==
ncount - 1) {
tail = tail.previous;
tail.next = null;
ncount--;
return;
}
Score temp =
tail;
for (int i = 0;
i < position - 1 && temp != null; i++) {
temp = temp.previous;
}
temp.next.previous = temp.previous;
temp.previous.next = temp.next;
ncount--;
}
}
public void display() {
Score current = head;
if (head == null) {
System.out.println("No Scores added yet.");
return;
}
System.out.println("\n Scores are :
");
while (current != null) {
System.out.print(current.item + " ");
current =
current.next;
}
}
}