I am to java and I am trying to implement a remove from double linked list method but I am struggling and not sure how to advance. The method removes data stored at the given node in the list. I have read that I need to account for cases where the the element being removed is the start or end but I am not sure how to go about. In general I am not sure if this is the right way to do it. My code/progress is posted below. If any could help, it would be appreciated. Thanks
PS I have a start and an end reference within the class and a size reference
public type removeAtTheIndex(int index)
{
type theData = null;
Node <type> current= start;
Node temp= new Node();
if (index >= 0 && index < size && start !=null)
{
for (int i=0; i < index && current.getNext()!= null; i++)
{
current=current.getNext();
}
if (current != null)
{
if (current == start)
{
}
else if (current == end)
{
}
else
{
theData= current.getData();
temp= current.getPrev();
temp.setNext(current.getNext());
current.getNext().setPrev(temp);
current.setData(null);
size--;
}
}
return theData;
}
I have changed the type
to Type
. Using lowercase for class names is not recommended in Java. I have added loads of comments in the hope that you will understand what is going on.
Note that this is not tested code. You may find bugs in it but I am confident that the essence of process is there.
public Type removeAtTheIndex(int index) {
// I want to return the data that was removed.
Type theData = null;
// Sanity checks.
if (index >= 0 && index < size && start != null) {
// Find the entry with the specified index.
Node<Type> current = start;
for (int i = 0; i < index && (current = current.getNext()) != null; i++) {
}
// Did we find it?
if (current != null) {
// Yes! Gather the contents.
theData = current.getData();
// Clear it.
current.setData(null);
// Special?
if (current == start) {
// Its the start one.
start = start.getNext();
// Detach it.
start.setPrev(null);
} else if (current == end) {
// Step end back one.
end = end.getPrev();
// Detach it.
end.setNext(null);
} else {
// Remove from within list.
Node prev = current.getPrev();
// Point it at my next.
prev.setNext(current.getNext());
// Point my next to new prev.
current.getNext().setPrev(prev);
}
// One less now.
size--;
}
}
return theData;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.