简体   繁体   中英

How do I delete the last occurrence in a circular linked list? (java)

I want to make a method that deletes the last occurrence of a value given in an argument in a circular linked list.
I tried to do it and this is my approach:

public void deleteLastOccurence(int value) {
        Element cur = this.head;
        Element prev = null;
        Element tmp = null;
        
        if(this.head == null)
            return;
        
        if(this.rear.data == value) {
            this.head = this.rear = null;
            return;
        }
        
//      while(cur != this.rear) {
            while(cur.next != this.head && cur.next.data != value) {
                prev = cur;
                tmp = cur.next;
//              cur = cur.next;
            }
//          cur = cur.next;
//      }
        prev.next = tmp.next;
    }  

But I don't think that I am deleting the last occurrence, because what if the value that I want to delete is right next to the same value.

Separate finding the node from deleting the node. The method is simplified to

public void deleteLastOccurrence(int value) {
  Element lastOccurrence = findLastOccurrence(value);
  if (null != lastOccurrence) {
    deleteElement(lastOccurrence);
  }
}

Assuming that a circular list means that the head.prev is the rear and the rear.next is the head . To find the last occurrence, start at the rear of the list and iterator towards the head . The last occurrence is thus the first match you encounter.

private Element findLastOccurrence(int value) {
  if (isEmpty()) {
    return null;
  }
  Element current = rear;
  do {
    if (current.value == value) {
      return current;
    }
    current = current.prev;
  } while (current != rear);  // we're back at the rear with no match
  return null;
}

The isEmpty() and deleteElement(Element) methods are left as an exercise for the reader.

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