PHP 数据结构

在此方法中,双向链表的最后一个节点被删除。例如 - 如果给定列表是 10->20->30->40 并且最后一个节点被删除,则列表将变为 10->20->30。

删除双向链表的最后一个节点涉及检查头为空。如果不为空,则检查接下来的头部是否为空。如果头下一个为空,则释放头,否则遍历链表的倒数第二个节点。然后,将倒数第二个节点的下一个链接到 NULL 并删除最后一个节点。

双向链表 - 删除最后一个节点

函数pop_back就是为此目的而创建的。这是一个3步过程

public function pop_back() {
  if($this->head != null) {
    
    //1.如果头不为空并且头的下一个
    //为空,释放头部
    if($this->head->next == null) {
      $this->head = null;
    } else {
      
      //2。否则,遍历到倒数第二个
      //列表元素
      $temp = new Node();
      $temp = $this->head;
      while($temp->next->next != null)
        $temp = $temp->next;
      
      //3。更改第二个的下一个
      //最后一个节点为null并删除
      //最后一个节点
      $lastNode = $temp->next;
      $temp->next = null; 
      $lastNode = null;
    }
  }
}

下面是一个完整的程序,它使用了上面讨论的删除双向链表最后一个节点的概念。

<?php
//节点结构
class Node {
  public $data;
  public $next;
  public $prev;
}

class LinkedList {
  public $head;

  public function __construct(){
    $this->head = null;
  }
  
  //在列表末尾添加新元素
  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;
    }    
  }

  //删除链表最后一个节点
  public function pop_back() {
    if($this->head != null) {
      if($this->head->next == null) {
        $this->head = null;
      } else {
        $temp = new Node();
        $temp = $this->head;
        while($temp->next->next != null)
          $temp = $temp->next;
        $lastNode = $temp->next;
        $temp->next = null; 
        $lastNode = null;
      }
    }
  }
  
  //显示列表内容
  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";
    }
  }   
};

//测试代码
$MyList = new LinkedList();

//在列表中添加四个元素。
$MyList->push_back(10);
$MyList->push_back(20);
$MyList->push_back(30);
$MyList->push_back(40);
$MyList->PrintList();

//删除最后一个节点
$MyList->pop_back();
$MyList->PrintList(); 
?>

上面的代码将给出以下输出:

The list contains: 10 20 30 40
The list contains: 10 20 30