PHP如何?雙鏈表刪除與插入節點的方法

來源:互聯網
上載者:User
這篇文章主要介紹了PHP實現雙鏈表刪除與插入節點的方法,結合執行個體形式分析了PHP雙鏈表的定義與節點操作相關實現技巧,需要的朋友可以參考下

具體如下:

概述:

雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個資料結點中都有兩個指標,分別指向直接後繼和直接前驅。所以,從雙向鏈表中的任意一個結點開始,都可以很方便地訪問它的前驅結點和後繼結點。一般我們都構造雙向迴圈鏈表。

實現代碼:

<?php class node{  public $prev;  public $next;  public $data;  public function __construct($data,$prev=null,$next=null){    $this->data=$data;    $this->prev=$prev;    $this->next=$next;  }}class doubleLinkList{  private $head;  public function __construct()  {    $this->head=new node("head",null,null);  }  //插入節點  public function insertLink($data){    $p=new node($data,null,null);    $q=$this->head->next;    $r=$this->head;    while($q){      if($q->data>$data){        $q->prev->next=$p;        $p->prev=$q->prev;        $p->next=$q;        $q->prev=$p;      }else{      $r=$q;$q=$q->next;      }    }    if($q==null){      $r->next=$p;      $p->prev=$r;    }  }  //從頭輸出節點  public function printFromFront(){    $p=$this->head->next;    $string="";    while($p){    $string.=$string?",":"";    $string.=$p->data;    $p=$p->next;    }    echo $string."<br>";  }  //從尾輸出節點  public function printFromEnd(){    $p=$this->head->next;    $r=$this->head;    while($p){    $r=$p;$p=$p->next;    }    $string="";    while($r){      $string.=$string?",":"";      $string.=$r->data;      $r=$r->prev;    }    echo $string."<br>";  }  public function delLink($data){    $p=$this->head->next;    if(!$p)    return;    while($p){      if($p->data==$data)      {        $p->next->prev=$p->prev;        $p->prev->next=$p->next;        unset($p);        return;      }      else{        $p=$p->next;      }    }    if($p==null)    echo "沒有值為{$data}的節點";  }}$link=new doubleLinkList();$link->insertLink(1);$link->insertLink(2);$link->insertLink(3);$link->insertLink(4);$link->insertLink(5);$link->delLink(3);$link->printFromFront();$link->printFromEnd();$link->delLink(6);

運行結果:

1,2,4,55,4,2,1,head沒有值為6的節點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.