Insert items into Custom LinkedList in Order
I'm trying to insert items into a custom linked list, while keeping the list in order.
My work up to now is this:
public class CustomList {
public CustomList() {
this.first = null;
}
public void insert(Comparable newThing) {
Node point = this.first;
Node follow = null;
while (point != null && point.data.compareTo(newThing) < 0) {
follow = point;
point = point.next;
}
if (point == null) {
Node newNode = new Node(newThing);
newNode.next = this.first;
this.first = newNode;
} else {
Node newNode = new Node(newThing);
newNode.next = point;
if (follow == null) {
this.first = newNode;
} else {
开发者_运维问答 follow.next = newNode;
}
}
}
private Node first;
private class Node {
public Comparable data;
public Node next;
public Node(Comparable item) {
this.data = item;
this.next = null;
}
}
}
The output I get from this looks like it orders parts of the list, then starts over.
Example (I'm sorting strings):
Instead of getting something like a,b,c,...,z
I get a,b,c,...,z,a,b,c,...,z,a,b,c,...,z
So it looks like it doesn't "see" the whole list at certain points.
This is part of a HW assignment, so I'd appreciate suggestions, but let me try to figure it out myself!
What happens if you insert an element which is greater than all your existing elements?
You want to insert the element at the end, but in fact you are inserting it at start. And any later elements will then inserted before this (if they are smaller), or again at start.
精彩评论