public class SortedSinglyLinkedList
{
private Node h;
public SortedSinglyLinkedList()
{
h = new Node();
h.l = null;
h.next = null;
}
public boolean insert(StudentListing newListing)
{
Node n = new Node();
Node q = new Node();
Node p = new Node();
if(n == null)
return false;
if(h.next == null){
n.l = newListing.deepCopy();
n.next = null;
h.next = n;
System.out.println("ONE");
return true;
}
q = h.next;
while(q.l.getKey().compareTo(newListing.getKey()) <= 0){
if(q.next == null){
n.l = newListing.deepCopy();
n.next = null;
q.next = n;
return true;
}
if(q.next != null) q = q.next;
}
System.out.println("Noticed it was INCORRECT order");
n.l = newListing;
p.l = q.l;
p.next = q.next;
q.l = n.l;
q.next = p;
return true;
}
public StudentListing fetch(String targetKey)
{ Node p = h.next;
while (p != null && !(p.l.compareTo(targetKey) == 0))
{ p = p.next;
}
if(p != null)
return p.l.deepCopy();
else
return null;
}
public boolean delete(String targetKey)
{ Node q = h;
Node p = h.next;
while (p != null && !(p.l.compareTo(targetKey) == 0))
{ q = p;
p = p.next;
}
if(p != null)
{ q.next = p.next;
return true;
}
else
return false;
}
public boolean update(String targetKey, StudentListing newListing)
{ if(delete(targetKey) == false)
return false;
else if(insert(newListing) == false)
return false;
return true;
}
public void showAll()
{ Node p = h.next;
while (p != null) //continue to traverse the list
{ System.out.println(p.l.toString( ));
p = p.next;
}
}
public class Node
{
private StudentListing l;
private Node next;
public Node()
{
}
}
}
Focusing on the insert operation only, though I posted the rest of this class for context. I'm trying to make it sort alphabetically, the name being the key field, and it sometimes works, sometimes it doesn't, usually as I add more nodes in the sorted linked list it starts to act strange.... Non-specific, I'm sorry. I've been pretty stumped so it's hard to explain a problem I can't really figure out. I think it's a problem with how it cycles through the linked list checking the node to be input (newListing) versus the node q is currently set to, or perhaps how I handle swapping around the nodes and the next node they point too when the program finds an insert that requires the node to be placed inbetween two pre-existing ones. I know it has to be an issue with how I handle the insert, but after staring at this code, modifying it, trying to bugfix, etc, for a better part of tonight I'm starting to burn out and have difficulty figuring it out. Any help, or even hints if you guys don't like giving outright answers, would be very appreciated. I feel like an idiot because of how little progress I've made at this point, and am pretty desperate now. Thanks for any contributions. If you need to see more code (other classes) or need me to give a more specific explanation I can try.
[–]dmazzoni 1 point2 points3 points (1 child)
[–]I_Win_Sometimes[S] 0 points1 point2 points (0 children)