You need to complete the iteration as well as the insertion. Assuming you are implementing a linked list and you have a public next
attribute at you ListElement
class.
public boolean insert(Person p){
ListElement element = new StackElement(p);
boolean inserted = false;
if(head == null){
head = element;
size = size + 1;
inserted = true;
return inserted;
}
ListElement temp = head;
ListElement prev = null;
while(temp != null){
if(temp.compareTo(element) < 0) {
if(prev != null) prev.next = element; //Keep the chain connected
element.next = temp; //Insert you element before temp
inserted = true;
break;
}
prev = temp;
temp = temp.next;
}
}
if(!inserted && temp == null && prev != null) { //You may want to insert it at the end of the list if no upper element is found.
prev.next = element; //Put it at the end.
inserted = true;
}
if(inserted) size = size + 1;
return inserted; //This should be true in any case but I left it for the case you want to avoid inserting the element at the end if its place is not found.
}
ListElement.next
could also be a private or protected attribute and be accessed through a getter like getNext()
.
I think you shouldn't return the inserted
value since if the element can't be place before any other it should be placed at the end of the list and therefore always being inserted. That is, this code is a better implementation of a sorted list:
public void insert(Person p){
ListElement element = new StackElement(p);
if(head == null){
head = element;
size = size + 1;
return;
}
ListElement temp = head;
ListElement prev = null;
boolean inserted = false;
while(temp != null){
if(temp.compareTo(element) < 0) {
if(prev != null) prev.next = element; //Keep the chain connected
element.next = temp; //Insert you element before temp
inserted = true;
temp = null;
} else {
prev = temp;
temp = temp.next;
}
}
}
if(!inserted && prev != null)
{
prev.next = element; //Put it at the end.
}
size = size + 1;
}
Concerning your delete
method, I think you are making things too complicated.
In your iteration you only have to keep two references: one for the previous element and another to the current.
If your first element is the one to be deleted then your prev
reference will be null
and you will have to update head
. Otherwise, you will need to update prev
next reference making it reference the element after current
:
public boolean delete(Person p){
boolean deleted = false;
PersonListElement current = head;
PersonListElement prev = null;
while(current != null && !deleted){
if(current.getValue().compareTo(p) == 0){
if(prev != null)
prev.setNext(current.getNext());
else
head = current.getNext();
deleted = true;
} else {
prev = current;
current = current.getNext();
}
}
if(deleted) size--;
return deleted;
}