restrict the user from entering a duplicate IDitem - java

so i have a data structure project assignment , that i need to create singly linked list and implement a swing + exception handling concept.
I create a super market list item , but i am having a problem of restricting the user from entering duplicate ID-item , when user enters the duplicate it id , i wish to have a message " duplicate ID not allowed "
here is my code in the "frame" class
if(B==b11)
try
{
al1.AddItem(Integer.parseInt(t1.getText()),t2.getText(),Integer.parseInt(t4.getText()),Double.parseDouble(t5.getText()));
JOptionPane.showMessageDialog(null,"Added");
}
catch(Exception x){
JOptionPane.showMessageDialog(panel,"Wrong input ,please renter the fields ", "Warning",
JOptionPane.WARNING_MESSAGE);
};
and this is my code in the "Node process" class
public void AddItem(int ID, String Name, int Q, double P)
{
if(head==null)
head=tail=new project6(ID,Name,Q,P,head);
else
{
project6 pred, tmp;
for(pred = head, tmp = head.next; tmp != null && ID > tmp.ProductID; pred = pred.next, tmp = tmp.next);
if(tmp != null)
pred.next = new project6(ID,Name,Q,P,tmp);
else
tail.next = tail = new project6(ID,Name,Q,P, null);
}
}

If you are adding elements to a List, you can use the contains() method; if not, you should write a comparable method that traverses your Node data structure.
Alternatively, you might want to consider adding elements to a Set, which precludes duplicates. TreeSet may a good concrete implementation, as it remains ordered. The add() implementation returns false if the "set already contains the element." You can use that information to throw a suitable exception.

Related

Derivative method is changing original list when it should be returning newList

I have an assignment where I am manipulating polynomials using linked lists. One portion of the assignment is to take the first, second and third derivatives of a polynomial. All my methods work individually. However, after running the first derivative method, it changes original input list to what the first derivative is–something I do not want.
Here is my method:
public ObjectList derivative(ObjectList list1) {
newList = new ObjectList();
ObjectListNode p = list1.getFirstNode();
while (p != null) {
Term t1 = (Term) p.getInfo();
if (t1.getExp() == 0) {
t1.setCoeff(0);
attach(0,0);
p = p.getNext();
}
else {
t1.setCoeff(t1.getCoeff()*t1.getExp());
t1.setExp(t1.getExp() - 1);
attach(t1.getCoeff(), t1.getExp());
p = p.getNext();
}
}
return newList;
}
As you can see, the return for the derivative method is newList. However, the method is changing the original list.
In my main, I have something like this:
ObjectList poly1;
System.out.println("\nEnter a polynomial (for derivatives): ");
poly1 = p.getPolynomial();
System.out.println("First derivative: ");
p.displayPoly(p.derivative(poly1));
System.out.println("\nTest:");
p.displayPoly(poly1);
poly1 ends up changing.
My input into the console I have been using is : 3x^4+2x^3+1x^2-1x^1+8x^0
This is probably an extremely simple mistake, but for some reason I cannot catch it. Thanks for any help, I appreciate it!
EDIT: The attach method in the derivative method:
private void attach (int coeff, int exp) {
Term t = new Term (coeff, exp);
newList.addLast(t);
}
You are only initializing the newList instance (with newList = new ObjectList()) without putting anything in it, and you are updating the terms of the input list list1.
You didn't post the code of ObjectList and ObjectListNode, so I can't say the exact methods you should call in order to add nodes to newList, but you should add a new node to newList for each node of the input list, initialize it to contain a copy of the respective Term of the input list, and update the Term of the newList instead of the Term of the input list.
EDIT :
You don't pass newList to attach, so the list you are adding terms to is not the same list you initialize in the derivative method. In addition, you shouldn't call setCoeff and setExp on the terms of the input list, since you don't want to change it.
Therefore you should replace :
t1.setCoeff(0);
attach(0,0);
with :
attach(0,0);
And replace :
t1.setCoeff(t1.getCoeff()*t1.getExp());
t1.setExp(t1.getExp() - 1);
attach(t1.getCoeff(), t1.getExp());
with :
attach(t1.getCoeff()*t1.getExp(), t1.getExp() - 1);
However, if you want to update the newList created in the derivative method, you should either pass the newList to the attach method, or cancel the attach method and move its content to the derivative method :
public ObjectList derivative(ObjectList list1) {
newList = new ObjectList();
ObjectListNode p = list1.getFirstNode();
while (p != null) {
Term t1 = (Term) p.getInfo();
if (t1.getExp() == 0) {
Term t = new Term (0,0);
newList.addLast(t);
p = p.getNext();
}
else {
Term t = new Term (t1.getCoeff()*t1.getExp(), t1.getExp() - 1);
newList.addLast(t);
p = p.getNext();
}
}
return newList;
}

Insert items in ascending order in a singly linked list in Java

I need to modify the insert method of my program so that it inserts items into a singly linked list in ascending order. I understand what a linked list is but have no clue how to insert the items in order. Here are my programs so far(not the entire program):
public class SinglySortedLinkedList
{ private Node h; // list header
public SinglySortedLinkedList()
{ h = new Node(); // dummy node
h.l = null;
h.next = null;
}
public boolean insert(Listing newListing)
{ Node n = new Node();
if(n == null) // out of memory
return false;
else
{
n.next = h.next;
h.next = n;
n.l = newListing.deepCopy();
return true;
}
}
here is the tester method:
public class MainSinglyLinkedList
{ public static void main(String[] args)
{ SinglySortedLinkedList boston = new SinglySortedLinkedList();
Listing l1 = new Listing("Bill", "1st Avenue", "123 4567" );
Listing l2 = new Listing("Al", "2nd Avenue", "456 3232");
Listing l3 = new Listing("Mike", "3rd Avenue", "333 3333");
boston.insert(l1); // test insert
boston.insert(l2);
boston.insert(l3);
boston.showAll();
l3 = boston.fetch("Mike"); // test fetch of Mike
System.out.println(l3.toString());
boston .delete("Al"); // test delete of Al
boston.showAll();
boston.update("Mike", l2); // test update of Mike to Al
boston.showAll();
System.exit(0);
}
}
Any ideas of some pseudocode of how to insert in ascending order by the names would be so great, thanks
I don't want to do your homework, but I'll give you hints. If you have more specific questions then, you will probably find answers in SO. In the unlikely situation where you don't, feel free to ask a new question ;)
First, you need to find the point in the list where you want to insert, and then insert your Node n (containing the new Listing) at that point. This can be done using a while loop, with a comparison between listings as a condition, which in english would be said:
while the listing of the current node is inferior to the listing I
want to insert, I keep on going
For how to do this kind of comparison on Strings in Java, have a look at the compareTo method.
Then, use your former piece of code to insert n there. See the note below to see what I have to say about it and your dummy Node.
Side note
You're using a "dummy node" for your list header, and always insert after that one.
This is probably not necessary, you could insert each new Node in place of h and make it point to the former h, which would be both cleaner and easier to read IMHO.
Instead of:
n.next = h.next;
h.next = n;
n.l = newListing.deepCopy();
You could have:
n.next = h; // here n's next points to the former head h
h = n; // now n in the new head referenced by h
n.l = newListing.deepCopy();
This way, you don't even need a dummy node anymore, null is fine to set the n.next field. It'll also probably simplify your fetch method.

coding with a singly linked list and bubble sort in java

I have a problem with my code, I have made a singly linked list class in which you can add, remove, modify, merge etc... however, I am attempting a simple bubble sort and have come across problems in which the list is not correctly sorted. here are some things to note:
it is a custom implementation of a linked list
the nodes of the singly linked list contain 2 things: a CustomerFile object with all the data for a customer and a 'next' node pointer to the next item in the list
the list is sorted in ascending order (A-Z) by the surname stored in the customer file of each node
the add record function inserts the nodes at the correct position in the list so that the list does not need to be sorted initially - however if the surname is changed, as part of the program, the list needs to be sorted again
I would rather not create a new list and re-use this insert record on that list to create a new list as this is memory intensive and my task is to be as efficient as possible
the very structure of the linked list cannot be changed - it is decided and I am too far to change to something such as an array
the list has a head node, it has next items but does not have a tail node. It has an appointed NULL next pointer to indicate the end pf the list
the code
public static void sortList()
{
if (isEmpty() == true)
{
System.out.println("Cannot sort - the list is empty");
}
else if (getHead().getNext() == null)
{
System.out.println("List sorted");
}
else
{
Node current = getHead().getNext();
CustomerFile tempDat;
boolean swapDone = true;
while (swapDone)
{
current = getHead().getNext();
swapDone = false;
while (current != null)
{
if (current.getNext() != null &&
current.getData().getSurname().compareTo(
current.getNext().getData().getSurname()) >0)
{
tempDat = current.getData();
current.setData(current.getNext().getData());
current.getNext().setData(tempDat);
swapDone = true;
}
current = current.getNext();
}
}
if (getHead().getData().getSurname().compareTo(
getHead().getNext().getData().getSurname()) >0)
{
current = getHead().getNext();
getHead().setNext(current.getNext());
setHead(current);
}
}
}
I would appreciate the feedback
Your code is an odd mixture, mostly swapping data but treating the head specially trying to swap it with the next by switching the links.
As noted in another answer, this last swap is not correctly implemented, but really there's no reason to treat the head specially if you're doing things by swapping the data.
All you have to do is start each traversal of the list at the head in the outer loop.
This yields a working solution:
public void sortList()
{
if (isEmpty())
{
System.out.println("An empty list is already sorted");
}
else if (getHead().getNext() == null)
{
System.out.println("A one-element list is already sorted");
}
else
{
Node current = getHead();
boolean swapDone = true;
while (swapDone)
{
swapDone = false;
while (current != null)
{
if (current.getNext() != null && current.getData().getSurname().compareTo(current.getNext().getData().getSurname()) >0)
{
CustomerFile tempDat = current.getData();
current.setData(current.getNext().getData());
current.getNext().setData(tempDat);
swapDone = true;
}
current = current.getNext();
}
current = getHead();
}
}
}
I've made this non-static because as noted in comments it wasn't clear to me how yours could work as a static. You may be able to make it static in your context.
I also changed a couple other minor things. It's never necessary to check a condition by code like
if (isEmpty() == true)
In Java, this is entirely equivalent to
if (isEmpty())
And tempDat doesn't need to be declared outside of where it's used.
I think the main issue here is that you start with
current = getHead().getNext()
With this code you will leave the head completely out of the sorting process and it could be the case that the data in here needs to go to the other end of the list, but in this case it will always be either the data in the head element, or be the data directly after the head node (the latter is due to your if statement at the end).
Try starting from the head of the list instead and see what that brings up.
You are not including the head in your sorting.
public static void sortList()
{
if (isEmpty() == true)
{
System.out.println("Cannot sort - the list is empty");
}
else if (getHead().getNext() == null)
{
System.out.println("List sorted");
}
else
{
Node current = getHead();
// Node current = getHead().getNext();
CustomerFile tempDat;
boolean swapDone = true;
while (swapDone)
{
current = getHead().getNext();
swapDone = false;
while (current != null)
{
if (current.getNext() != null && current.getData().getSurname().compareTo(current.getNext().getData().getSurname()) >0)
{
tempDat = current.getData(); // td -> objectA, cd -> objectA
current.setData(current.getNext().getData()); // cd -> objectB
current.getNext().setData(tempDat); // nd -> td -> objectA
swapDone = true;
}
current = current.getNext();
}
}
//if (getHead().getData().getSurname().compareTo(getHead().getNext().getData().getSurname()) >0)
//{
// current = getHead().getNext(); // current -> head+1
// getHead().setNext(current.getNext()); //head+1 -> head+2
// setHead(current); // head -> head+1
//}
}
}
Also there is a error in the commented out code above. Applying that code drops a node.
// list: a -> b -> c -> d
current = getHead().getNext(); // current = b
getHead().setNext(current.getNext()); // a -> c
setHead(current); // head = b
// list: b -> c -> d
// and nothing points to 'a' anymore
Rather then swapping data you should try swapping nodes. If you go about that approach you should find a better solution.

Search by inorder in binary search tree

I use inorder to show result of search name which store in binary search tree but when i run it example i have: Employee name "abc" and "ab" and i input name ="abc" it show 2 of them.Anyone can help me what is my fault :( ty
public void searchFull(String name) {
EmployeeSLLNode p = root;
n=0;
if (p != null) {
inorder(p.left);
if(p.info.getFullname().equals(name)) {
n++;
System.out.printf("%2s %-5s %-8s %-6s %-6s%n", n, p.info.getID(), p.info.getFullname(), p.info.getAge(), p.info.getGender());
}
inorder(p.right);
}
}
In-order traversal is equivalent to iterating a TreeMap's entrySet.
final Map<String, Employee> employees = new TreeMap<String, Employee>();
...
for (final Map.Entry<String, Employee> entry : employees.entrySet()) {
/* iterating in-order */
}
TreeMap simply uses a binary search tree (in particular, according to the specification, a red-black tree). Consider using it instead of rolling your own solution ;-)
That being said, if you're intent on rolling your own, maybe try something like this...
public EmployeeSSLnode search(final EmployeeSSLnode root, final String name) {
EmployeeSSLnode left;
return root == null
? null
: (left = search(root.left, name)) == null
? root.info.getFullname().equals(name)
? root
: search(root.right, name)
: left;
}
I think this is what you can do.But ensure that your your tree doesn't have the duplicate names.
public void searchFull(EmployeeSLLnode p, String name) {
if (p == null)
return;
searchFull(p -> left, name);
if (p.info.getFullname().equals(name)) {
//This is the node do other stuff here
return;
}
searchFull(p -> right, name);
}
Also it would be better to do general search in BST instead of searching through Inorder. Inorder searcing in BST would actually ruin the whole purpose of BST. Compare the input Name with node using compareTo() method of String class and depending on whether name is alphabetically later or earlier move either to right or left.
Most of this code should be inside the inorder() method. Undoubtedly it actually is, so you have two prints, so you get two outputs. All the searchFull() method should do is call inorder(root).

adding and removing from a singly linked list

I thought I had understanding of this in my previous question about linked lists, but I was terribly mistaken, I'm just as lost as I was when I initially posted.
I realize that I'm technically asking two questions, but hopefully getting at least one should make the other easy (assuming they are just reverse of each other).
I have 3 classes already given to me, they are:
SLinkedList.java
package chapter3.linkedList;
public class SLinkedList<V> {
// instance variables. Add the tail reference.
protected Node<V> head, tail;
protected long size;
// methods, empty list constructor first
public SLinkedList () {
head = null;
tail = null;
size = 0;
} // end constructor of a SLinkedList
// method to add nodes to the list. Storage space for the node
// is already allocated in the calling method
public void addFirst (Node<V> node) {
// set the tail only if this is the very first node
if (tail == null)
tail = node;
node.setNext (head); // make next of the new node refer to the head
head = node; // give head a new value
// change our size
size++;
} // end method addFirst
// addAfter - add new node after current node, checking to see if we are at the tail
public void addAfter (Node<V>currentNode, Node<V>newNode) {
if (currentNode == tail)
tail = newNode;
newNode.setNext (currentNode.getNext ());
currentNode.setNext (newNode);
// change our size
size++;
} // end method addAfter
// addLast - add new node after the tail node. Adapted from Code Fragment 3.15, p. 118.
// Mike Qualls
public void addLast (Node<V> node) {
node.setNext (null);
tail.setNext (node);
tail = node;
size++;
} // end method addLast
// methods to remove nodes from the list. (Unfortunately, with a single linked list
// there is no way to remove last. Need a previous reference to do that. (See
// Double Linked Lists and the code below.)
public Node<V> removeFirst () {
if (head == null)
System.err.println("Error: Attempt to remove from an empty list");
// save the one to return
Node<V> temp = head;
// do reference manipulation
head = head.getNext ();
temp.setNext(null);
size--;
return temp;
} // end method removeFirst
// remove the node at the end of the list. tail refers to this node, but
// since the list is single linked, there is no way to refer to the node
// before the tail node. Need to traverse the list.
public Node<V> removeLast () {
// // declare local variables/objects
Node<V> nodeBefore;
Node<V> nodeToRemove;
// make sure we have something to remove
if (size == 0)
System.err.println("Error: Attempt to remove fron an empty list");
// traverse through the list, getting a reference to the node before
// the trailer. Since there is no previous reference.
nodeBefore = getFirst ();
// potential error ?? See an analysis and drawing that indicates the number of iterations
// 9/21/10. size - 2 to account for the head and tail nodes. We want to refer to the one before the
// tail.
for (int count = 0; count < size - 2; count++)
nodeBefore = nodeBefore.getNext ();
// save the last node
nodeToRemove = tail;
// now, do the pointer manipulation
nodeBefore.setNext (null);
tail = nodeBefore;
size--;
return nodeToRemove;
} // end method removeLast
// method remove. Remove a known node from the list. No need to search or return a value. This method
// makes use of a 'before' reference in order to allow list manipulation.
public void remove (Node<V> nodeToRemove) {
// declare local variables/references
Node<V> nodeBefore, currentNode;
// make sure we have something to remove
if (size == 0)
System.err.println("Error: Attempt to remove fron an empty list");
// starting at the beginning check for removal
currentNode = getFirst ();
if (currentNode == nodeToRemove)
removeFirst ();
currentNode = getLast ();
if (currentNode == nodeToRemove)
removeLast ();
// we've already check two nodes, check the rest
if (size - 2 > 0) {
nodeBefore = getFirst ();
currentNode = getFirst ().getNext ();
for (int count = 0; count < size - 2; count++) {
if (currentNode == nodeToRemove) {
// remove current node
nodeBefore.setNext (currentNode.getNext ());
size--;
break;
} // end if node found
// change references
nodeBefore = currentNode;
currentNode = currentNode.getNext ();
} // end loop to process elements
} // end if size - 2 > 0
} // end method remove
// the gets to return the head and/or tail nodes and size of the list
public Node<V> getFirst () { return head; }
public Node<V> getLast () { return tail; }
public long getSize () { return size; }
} // end class SLinkedList
There's also Node.java
package chapter3.linkedList;
public class Node<V>
{
// instance variables
private V element;
private Node<V> next;
// methods, constructor first
public Node ()
{
this (null, null); // call the constructor with two args
} // end no argument constructor
public Node (V element, Node<V> next)
{
this.element = element;
this.next = next;
} // end constructor with arguments
// set/get methods
public V getElement ()
{
return element;
}
public Node<V> getNext ()
{
return next;
}
public void setElement (V element)
{
this.element = element;
}
public void setNext (Node<V> next)
{
this.next = next;
}
} // end class Node
and finally GameEntry.java
package Project_1;
public class GameEntry
{
protected String name; // name of the person earning this score
protected int score; // the score value
/** Constructor to create a game entry */
public GameEntry(String name, int score)
{
this.name = name;
this.score = score;
}
/** Retrieves the name field */
public String getName()
{
return name;
}
/** Retrieves the score field */
public int getScore()
{
return score;
}
/** Returns a string representation of this entry */
public String toString()
{
return name + ", " + score + "\n";
}
}
EDIT POINT
I created a driver called Scores.java, in it so far all I have is **I have added what I THINK i need for the classes, I'm probably wrong though:
package Project_1;
import chapter3.linkedList.*;
import java.util.*;
/** Class for storing high scores in an array in non-decreasing order. */
public class Scores
{
//add function
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;
}
//remove function
public void remove(int i)
{
}
//print function
/*gameenter printing;
printing=node.Getelement; //pseudo code for making it work right
print(printing.getscore)
print(print.getname)
*/
public void print(SLinkedList<GameEntry> scores)
{
Node<GameEntry> currentNode = scores.getFirst();
GameEntry currentEntry = currentNode.getElement();
System.out.printf("[");
for(int i = 0; i < scores.getSize(); i++)
{
System.out.printf(", %s", currentEntry.toString());
currentNode = currentNode.getNext();
currentEntry = currentNode.getElement();
}
System.out.println("]");
}
}
I have my test driver called ScoresTest.java, that I have pretty much filled out:
package Project_1;
import chapter3.linkedList.SLinkedList;
public class ScoresTest {
/**
* #param args
*/
public static void main(String[] args)
{
SLinkedList<GameEntry> highScores = new SLinkedList<GameEntry>(); //Linked List for Game Entry
GameEntry entry;
Scores rank = new Scores();
entry = new GameEntry("Flanders", 681);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Krusty", 324);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Otto", 438);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Bart", 875);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Homer", 12);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Lisa", 506);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Maggie", 980);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Apoo", 648);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Smithers", 150);
highScores = rank.add(entry, highScores);
entry = new GameEntry("Burns", 152);
highScores = rank.add(entry, highScores);
System.out.println("The Original High Scores");
rank.print(highScores);
entry = new GameEntry("Moe", 895);
highScores = rank.add(entry, highScores);
System.out.println("Scores after adding Moe");
rank.print(highScores);
//highScores = rank.remove(4);
System.out.println("Scores after removing Apoo");
rank.print(highScores);
}
}
That's entirely finished, pretty sure I have nothing left to add for it.
I'm not looking for someone to answer it for me, but I have no clue where to start or how to make the add or remove function, in any way. This is an intermediate course, the book does nothing for explaining linked lists (go ahead and look for yourself if you don't believe me, text is called Datastructures and Algorithms in Java, 5th edition). It shows how to do such with an array quite easily...which works perfectly for a linked list, but apparently the teacher does not want us doing it this way, so sadly I am now utterly lost on how to do this.
I've tried looking at other peoples answers on here, and google, and so far nothing has clicked or made any sense at all, I just can't grasp how it works, and the teacher's explanation and example was only to draw boxes on the board, I've never seen a sort, add, or remove function coded for a linked list...can't know what I've not been taught or can't locate.
Any help is greatly appreciated, and thank you in advance!
EDIT
I looked at the import java.util.*; and the commands within it for linked lists, they seem painfully easy. to remove I'd just use list.sublist(i, i).clear(); and the value I wish to remove is removed, super easy, it seems to be just trying to utilize the slinkedlist.java and node.java, I just can't seem to follow them in any way shape or form. I believe the teacher did indeed write them, and I've tried asking for his assistance, stayed 2 hours after class trying to get any understanding from him, and as you can see it did not help much at all. Thank you again for the assistance!
EDIT
I also apologize if this seems like it is vague, but I don't have a specific point where my confusion seems linked, I understand linked lists if we're talking about the java.util.linkedList;, but as far as using what I've been given in this circumstance, I can't follow the logic at all, leaving me quite lost and unsure of where to begin.
In pseudo-code (please note I am not including bound checking etc, simply the logic)
To add a node to the front of the list:
newNode->nextNode = startNode
startNode = newNode
To add to a specific index:
index = 0
currentNode = startNode
// find the node in the list. here you will need to do all kinds of bound checking
while index is less than position
currentNode = currentNode.nextNode // move your node pointer to the position
increment index
// so here we basically insert the new node into the list. what needs to happen is
// to NOT break the list by forgetting the node after the current node. this is why
// we first set the new nodes' next one, to the current nodes' (the one already in
// the list) next node. this way, we still have all the information we need. then,
// when we set the current nodes' next node to the new node, we essentially "break"
// the link and "repair" it by adding the new link.
newNode.nextNode = currentNode.nextNode // some more bound checking required
currentNode.nextNode = newNode
To remove from a specific index:
index = 0
delNode = startNode
// find the node in the list. here you will need to do all kinds of bound checking
while index is less than (position - 1)
delNode = delNode.nextNode // move your node pointer to the position
increment index
delNode.nextNode = delNode.nextNode.nextNode
// that's it. by setting the node's (before the one you whish to delete)
// next node to the node AFTER the one you want to delete, you basically
// "skip" over that node. since it is no longer referenced, the garbage
// collector will take care of the rest. if you wish to return that node
// you can do it quite easily by remembering it.
storeNode = delNode.nextNode // some more bound checking required
delNode.nextNode = delNode.nextNode.nextNode // some more bound checking required
// now you still have a reference to the deleted node in storeNode
UPDATE
OK, so if I understand correctly, you need to create a linked list that stores scores in a ascending order. As far as I can see, the entire linked list has been implemented for you, you simply need to use the classes provided, and add the logic in Scores.java to keep the list sorted.
First off, I see your nodes are not comparable. If you are at all allowed to change the source given to you, I would suggest having them implement Comparable<Node> and also override the equals(Object o) so that you have logic to compare them. Two nodes can contain the same element, but that does not mean that they are equal.
Please note the change in the method signatures!
//add function
public void add(Node<GameEntry> score) {
// adding is where you now want to keep everything sorted. so I highly
// recommend that you implement `Comparable` as I mentioned above. if not,
// you have to put the logic in here.
Node<GameEntry> currentNode = highScored.getFirst();
Node<GameEntry> prevNode = null;
// if the list is empty, or the new node must go in before the head,
// simply add it as the head.
if (highScores.size() == 0 || score.compareTo(currentNode) < 0) {
highScores.addFirst(score);
}
// search for the position of the new node. while the node has a higher score
// than the current node, we need to continue on so we can place it in the
// correct place.
while (currentNode != null && currentNode.compareTo(score) > 0) {
prevNode = currentNode;
currentNode = currentNode.getNext();
}
// if the currentNode is null, it means it is the highest score, so
// we can simply add it to the end
if (currentNode == null) {
highScores.addLast(score);
} else {
// otherwise just add it after the correct node
highScores.addAfter(prevNode, score);
}
}
//remove function
public void remove(Node<GameEntry> score) {
// removing an element should be as described above. if you keep
// your list sorted during the ADD method, removing any element
// should not break the order.
// find the element - removal from a linked list is O(n),
// since we need to know what the element BEFORE the one
// is that you want to remove. assuming you have implemented
// the equals method to check equality of nodes:
Node<GameEntry> currentNode = highScores.getFirst();
Node<GameEntry> prevNode = null;
while (currentNode != null && !currentNode.equals(score)) {
prevNode = currentNode;
currentNode = currentNode.getNext();
}
// if currentNode is null, the node we wanted to remove was not
// in the list.
if (currentNode == null) {
System.out.println("Node not found");
return;
}
// now, we need to check if there is a node after the one we want
// to remove.
if (prevNode.getNext().getNext() != null) {
// if there is, we follow the logic from the pseudo code
prevNode.setNext(prev.getNext().getNext());
} else {
// if not, we only need to remove the last entry (since the
// one we want to remove is the last one)
highScores.removeLast();
}
}
IMPORTANT
Please just double check the logic here. I did it really quickly without an IDE as I'm not at my development computer at the moment. If anyone finds any issues, please leave a comment and I'll fix it.
If this is not exactly what you asked (your question is a bit vague), let me know.
UPDATE 2
Read up on Comparators here, here and here.

Categories

Resources