Reputation: 1889
Reviewing my data structures, for some new job interview requirements. So I have a delete method for the Linked-List.
public Link delete(int key) {
Link current = first;
Link previous = first;
while(current.iData != key) {
if(current.next == null)
return null;
else {
previous = current;
current = current.next;
}
}
if(current == first)
first = first.next;
else
// just bypass it
previous.next = current.next;
return current;
}
I think I understand it so far. But I get curious around this line.
// just bypass it
previous.next = current.next;
Why don't we override the head
(in this example represented as first
) with the previous
? Or Would be that wrong logic? like
// just bypass it
previous.next = current.next;
first=previous;
I mean previous
and current
are just pointers to iterate the list. And the real data after the deletion is located in the first
right? Sorry if that would be weird to think in that why. Sometimes my weird intuition just comes out while studying algorithms mainly because I'm sort of weak
Upvotes: 0
Views: 98
Reputation: 230
Doing so will cause your linked list to lose all the nodes that come before the previous. If you had a linked list with the following values:
[1, 2, 3, 4, 5, 6, 7, 8]
and you called delete(7)
, your head will point to 6
, and you'll have a linked list of [6, 8]
.
Upvotes: 1