PHP Data Structures - Doubly Linked List Other Related Topics

PHP - Delete all nodes of the Doubly Linked List



Deleting all nodes of a doubly linked list requires traverse through the list and deleting each node one by one. It requires creating a temp node pointing to the head then move the head to head next. After that delete the temp node. Repeat the process till the head becomes null.

The function deleteAllNodes is created for this purpose. It is a 2-step process.

public function deleteAllNodes() {
  
  //1. create a temp node
  $temp = new Node();

  //2. if the head is not null make temp as head and 
  //   move head to head next, then delete the temp,
  //   continue the process till head becomes null
  while($this->head != null) {
    $temp = $this->head;
    $this->head = $this->head->next;
    $temp = null;
  }

  echo "All nodes are deleted successfully.\n"; 
}  

The below is a complete program that uses above discussed concept of deleting all nodes of a doubly linked list which makes the list empty with size zero.

<?php
//node structure
class Node {
  public $data;
  public $next;
  public $prev;
}

class LinkedList {
  public $head;

  public function __construct(){
    $this->head = null;
  }
  
  //Add new element at the end of the list
  public function push_back($newElement) {
    $newNode = new Node();
    $newNode->data = $newElement;
    $newNode->next = null;
    $newNode->prev = null; 
    if($this->head == null) {
      $this->head = $newNode;
    } else {
      $temp = new Node();
      $temp = $this->head;
      while($temp->next != null) {
        $temp = $temp->next;
      }
      $temp->next = $newNode;
      $newNode->prev = $temp;
    }    
  }

  //delete all nodes of the list
  public function deleteAllNodes() {
    $temp = new Node();
    while($this->head != null) {
      $temp = $this->head;
      $this->head = $this->head->next;
      $temp = null;
    }
    echo "All nodes are deleted successfully.\n";
  }   

  //display the content of the list
  public function PrintList() {
    $temp = new Node();
    $temp = $this->head;
    if($temp != null) {
      echo "The list contains: ";
      while($temp != null) {
        echo $temp->data." ";
        $temp = $temp->next;
      }
      echo "\n";
    } else {
      echo "The list is empty.\n";
    }
  }   
};

// test the code  
$MyList = new LinkedList();

//Add four elements in the list.
$MyList->push_back(10);
$MyList->push_back(20);
$MyList->push_back(30);
$MyList->push_back(40);

//Display the content of the list.
$MyList->PrintList();

//delete all nodes of the list
$MyList->deleteAllNodes();

//Display the content of the list.
$MyList->PrintList();
?>

The above code will give the following output:

The list contains: 10 20 30 40 
All nodes are deleted successfully.
The list is empty.