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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With