2

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 enter image description here

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.