php线性表小例子

<?php
/*

* 类名:LNode

* 功能:线性表的链式存储实现

* @author xxy

*/

ini_set('display_errors',1);
error_reporting(E_ALL);

class Node {
    public  $key = null;
    public  $data = null;     //存储数据元素
    public  $next = null;     //存储下一个数据元素的地址
}

class LinkList{
   private $head = null;
   private $end = null;
   public function insert($key, $data){
        $node = new Node();
        $node->key = $key;
        $node->data = $data;

        if($this->end==null){
          $this->end = $node;
          
        }else{
          $this->end->next =  $node;
          $this->end = $node;
        }
       if ($this->head == null){
            $this->head = $node;
       }
       return $node;
    }
  

  public function del_node($key){
      $node = $this->head;
      //echo $node; exit;
      $pre_node = null;
      
      while ( $node != null ){
          
          if ($node->key == $key){
              if($pre_node == null ){

                      $this->head = $node->next;
                      //$this->end;
                      if ($this->end == $node){

                          $this->end = null;
                      }
              }else{

                $pre_node->next = $node->next;

              }
             
              break;
          }

          $pre_node = $node;
          $node = $node->next;
      }
      
  }
  public function select($key){
       $node = $this->head;
      //echo $node; exit;
       $pre_node = null;

      while ( $node != null ){
          
          if ($node->key == $key){        
              $node_data = $node->head->data;
              break;
          }else{

          $pre_node = $node;
          $node = $node->next;
          }
      }
      return  $node_data;
  }
}

function test_link_insert_end(){
    $link = new LinkList();
    $info = array();
    for($i=1;$i<5;$i++) {

      $link->insert($i, $i);
       
        
    }
    return $link;
}
$link = test_link_insert_end();

print_r($link);
$s = $link->select(2);

$s = $link->del_node(3);
print_r($link);
print_r($s);
?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值