as far as I can see, you can do:
If your list is a double linked.
But how do you do it with a single linked list? I have tried a lot of things, with no avail :( I simply get it to remove a specific index instead or it does nothing at all
Start at the beginning of the list. Maintain a reference to the current item (currentItem
) and the previous item (previousItem
). Linearly search for the item that you want to remove always walking with previousItem = currentItem, currentItem = currentItem.Next
. If the item that you want to remove is the head of the list, reassign the head of the list to currentItem.Next
. Otherwise, set previousItem.Next = currentItem.Next
. If necessary (as you say, in a non-GC environment) dispose of currentItem
.
Basically you are using previousItem
to mimic the behavior of a currentItem.Previous
in the case of a doubly-linked list.
Edit: This is a correct implementation of Delete
:
public void Delete(int rangeStart, int rangeEnd) {
Node previousNode = null, currentNode = Head;
while (currentNode != null) {
if (currentNode.Data >= rangeStart && currentNode.Data <= rangeEnd) {
if (previousNode == null) {
Initial = currentNode.Next;
}
else {
previousNode.Next = currentNode.Next;
}
}
else {
previousNode = currentNode;
}
currentNode = currentNode.Next;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With