Reputation: 31252
I have this method from lecture on removing elements from linkedList
at specified index
.
I understand how the method works, but I do not understand why the for-loop
leaves the current node pointer
two index before the desired index.
Here is the method:
public void remove(int index) {
if (index == 0) {
// removing the first element must be handled specially
front = front.next;
} else {
// removing some element further down in the list;
// traverse to the node before the one we want to remove
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
// change its next pointer to skip past the offending node
current.next = current.next.next;
}
}
The for-loop
goes from 0 to < index-1
, while I thought it should go from 0 to < index
. In this way, the pointer is at one index
before the index
that needed to be deleted. However, the above method works fine.
For eg:
in the below LinkedList
Lets consider removing Node C
. By the above loop-construct, current pointer
will be pointing at Node A
and current.next
will be Node B
. current.next.next
will be Node C
. Doing current.next=current.next.next
will result in Node B
deletion rather than Node C
.
I think something is wrong with my understanding, can somebody explain?
Upvotes: 2
Views: 22409
Reputation: 279990
The for-loop goes from 0 to < index-1
In your example, removing C
means index is 2
. So i
only goes to 0
, since 1
is not < 1
.
current
starts at A
, the for
loops once and current
goes to B
.
current
is B
, so current.next.next
is D
, which effectively removes C
.
Upvotes: 2