Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 227
Teemo Avatar asked Oct 09 '16 20:10

Teemo


People also ask

What are the 3 conditions in deleting a node in a linked list?

Delete Node To delete a node from linked list, we need to do following steps. 1) Find previous node of the node to be deleted. 2) Change the next of previous node. 3) Free memory for the node to be deleted.

How do you remove an object from a linked list?

Type 1: remove() Method It is used to remove an element from a linked list. The element is removed from the beginning or head of the linked list. Parameters: This function does not take any parameter. Return Value: This method returns the head of the list or the element present at the head of the list.


1 Answers

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

like image 50
willian ver valem Avatar answered Oct 09 '22 05:10

willian ver valem