简体   繁体   中英

How to delete the first element in a linked list?

I am trying to write a function delete() that takes a linked list and deletes the Kth element from the list. My code is below.

public void delete(int k){
  Node current = head;
  for (int i = 0; i < k; i++){
      if(current == null || current.next == null){ //check if list is empty or k is out of bounds

          throw new IndexOutOfBoundsException();
          }
      else 
      {
          current = current.next; // Move pointer to k position
      }
  }
  remove(current.item);
  N--;  
  }

public void remove(E e) {
if (e == null)
  throw new NullPointerException();

// (*) special case (2/one node with e)
if (head != null && head.item.equals(e)) {
  head = null;
  N--;
}
else { // (*) general case (3) -- this also covers the case for empty list
  Node temp;
  // Step 1: bring temp to one node before the node with e.
  for (temp = head; temp != null && !temp.next.item.equals(e);
       temp = temp.next) {} // empty body
  // Step 2: if temp is still in the list, then remove
  if (temp != null) {
    temp.next = temp.next.next;
    --N;
  }
}

}

So far my code works as expected when I run a command such as lst1.delete(1) or lst1.delete(2) in main. However, when I run lst1.delete(0) , it deletes the entire linked list. I cannot figure out why lst1.delete(0) is deleting the entire linked list, but I think is has something to do with the for-loop. The for-loop is loops up until one less than k. If I pass in 0, then perhaps it is deleting the head entry point, which is deleting the entire list?

My question is, can anybody please tell me how I can change my code so that when I run lst1.delete(0) , it just deletes the first element in the linked list, and not the entire linked list?

This should fix your issue. You are setting

head = null; 

if the item to remove is the head, but what you should do is,

if(head.next() != null) {
    head = head.next();
}
else {

    head = null;
}

This will point the head to head + 1 item, unless head is the only item in the list. in that case we should set head to null.

public void delete(int k) {

    Node current = head;

    for (int i = 0; i < k; i++){

        if(current == null || current.next == null) { //check if list is empty or k is out of bounds

            throw new IndexOutOfBoundsException();
        }
        else {

            current = current.next; // Move pointer to k position
        }
    }

    remove(current.item);

    N--;  
}

public void remove(E e) {

    if (e == null) {

        throw new NullPointerException();
    }

    // (*) special case (2/one node with e)
    if (head != null && head.item.equals(e)) {

        //Your issue was here
        if(head.next() != null) {

            head = head.next();
        }
        else {

            head = null;
        }

        N--;
    }
    else { // (*) general case (3) -- this also covers the case for empty list

        Node temp;

        // Step 1: bring temp to one node before the node with e.
        for (temp = head; temp != null && !temp.next.item.equals(e);

            temp = temp.next) {} // empty body

            // Step 2: if temp is still in the list, then remove
            if (temp != null) {

                temp.next = temp.next.next;
                    --N;
            }
        }
    }
}

You problem is here

if (head != null && head.item.equals(e)) {
     head = null;
     N--;
}

if you use lst1.delete(0) then head.item.equals(e) become true as you pass head to remove() . Then your entire linked removed.

One fix would be

 if (head != null && head.item.equals(e)&&head.next==null) {
     head = null;
     N--;
}

Here extra check head.next==null ensure that there have only one element in the linked list.

1) delete(0). delete never enters loop because i less than k is true straight away. So you remove head.item. 2) Then remove special case 2 sets head = null.

That's 2 mistakes. No offence but your code is a mess. Sit down with diagrams and try puzzling it from scratch again. Someone else doing it for you will teach you nothing except how to give up on a programming problem early.

This reason is because when k = 0, the loop is never entered. As a result, current is not updated to point to the right one.

I figured out another method that does not even call the remove method. Since I was not the one who originally wrote the remove method, I prefer the code below over the others only because it stays within its self as far as method calling goes.

public void delete(int k){
  //instance variable
  Node current = head;

  if(current == null || current.next == null){ //check if list is empty

      throw new NullPointerException();
      }

  if (k < 0 || k >= size()){                  // check if k is out of bounds

      throw new IndexOutOfBoundsException();
      }

  if (k == 0){                                // this handles k = 0 condition
      head = head.next;
  }

  else

  for (int i = 0; i < k-1; i++){              // otherwise, if K != 0,
      current = current.next;                 // move pointer to k position

  }

  if (current != null) {
        current.next = current.next.next;
  }

  N--;  

  }

This gave me the output I was hoping for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM