سؤال

I want to delete k number element from list. I would do it like below (pseudocode)

delete(L,k)

x <- L.head
i <- 1
while(i < k-1 AND x.next != NULL)
    x<-x.next
    i <- i+1
if(i = k-1 AND x.next != NULL)
    if(x.next.next != NULL)
        x.next <- x.next.next
    else if(x.next.next = NULL)
        x.next = NULL

My purpose is: if k is last, then delete k-1.next. If k is not last, then make k-1.next pointing to k+1. Is it good idea?

هل كانت مفيدة؟

المحلول

Your linked list delete method seems mostly correct.

Why are you counting from one? Do you want the head to be a dummy node, which contains no value (then you can keep an empty list) if so try:

i=0
while(i <= k && x.next != null)

Then when you want to delete the first item (k=1) the while loop will execute once. Otherwise use

while(i = k && x.next !=null)

Similarly in the first if statement change k-1 to k.

I don't know why you use the IF ELSE, because if it x.next.next is null you are just assigning null anyway.

The problem is with your counter values vs the delete values. Try deleting the first item of your list.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top