Teemo
Teemo

Reputation: 111

Delete the element at index N, LinkedList

This is homework

I have been asked to delete the kth element from a LinkedList. I have also been given its size an int N. The question is how do I update the size of my list after deleting the node at position "k"? If there is something wrong with the logic in my code, please mention it.

I don't want the solution just guidance, thanks.

int N;               
Node first;         

// delete the kth element (where k is between 0 and N-1 inclusive)
public void delete (int k) {
    if (k < 0 || k >= N)
        throw new IllegalArgumentException();
    Node x = first;
    if( k == 0){
        first = x.next;
        N = N - 1;
    }
    for(int i = 1; i < k; i++){
        x = x.next;
        N = N - 1;
    }
    x.next = x.next.next;
    N = N - 2;
}

I think I might be doing something wrong with the list size (int N).

Upvotes: 7

Views: 2052

Answers (3)

willian ver valem
willian ver valem

Reputation: 395

When you delete a node, you just need to change the previous Node's next to the (new) next node in k and decrement N (N--) to update the list size.

EDIT

Also pay attention on your for loop you are changing the next of all nodes before node k

Upvotes: 2

Sondering Narcissist
Sondering Narcissist

Reputation: 419

Try using the list.remove(Object obj) method defined in LinkedList. To get the object at the k-th element, you can use list.get(int index). Once you find the k-th element, consider breaking or returning to avoid any concurrent modification problems or index-related errors.

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

Consider making two cases: k == 0 and the rest. The size is given by N so the new size should be N - 1.

Node x = first; // What a name
if (k == 0) {
    first = x.next; // Could be first = first.next
    N = N - 1;
    // Are you done here?
}

for (int i = 1; i < k; i++) {
    x = x.next;
    // Really? N = N - 1;
}
x.next = x.next.next;
// Really? N = N - 2;
N = N - 1;

Upvotes: 0

Related Questions