zoukankan      html  css  js  c++  java
  • PHP 实现单链表

    数据结构是计算机存储、组织数据的方式,结构不同那么数据的检索方式和效率都不一样,

    常用的数据结构有  数组 、栈 、队列 、链表 、树、堆

    今天讲下单链表,单链表是一种链式存取的数据结构, 跟顺序链表完全部一样 是一种非顺序结构存储

    单链表是结点表示数据,结点包括数据和后继元素构成(用来存放下一个节点的位置)

    链表的缺点失去顺序表读取的优点,增加了结点的地址,空间开销比较大,但比顺序存储空间的使用要相对灵活。

    链表主要操作主要是遍历操作,效率降低了

    单链表的表现形式,这种结构不像顺序结构连续存储,是一种非连续,非顺序的存储结构  例如以下,

    增加节点   删除节点 

    代码实现

     1 <?php
     2 class node{
     3      public $id;
     4      public $next;
     5      public function __construct($id=null,$next=null){
     6          $this->id=$id;
     7          $this->next=$next;
     8      }
     9 }
    10 class singleLinkedList
    11 {
    12     public $header = null;
    13 
    14     public function addLink($node,$index=0)
    15     {   $i = 0;
    16         if(is_null($this->header))
    17         {
    18             $this->header = $node;
    19         }else{
    20             $curr = $this->header;
    21             while ($curr->next != null) 
    22             {
    23                 $i ++;
    24                 if($i<=$index)
    25                 {
    26                     break;
    27                 }
    28                 $curr = $curr->next;
    29              }
    30             $node->next = $curr->next;
    31             $curr->next = $node; 
    32         }
    33 
    34     }
    35 
    36     public function delLink($index=1)
    37     {
    38         $i = 1;
    39         $curr = $this->header;
    40         while ($curr->next != null) 
    41         {
    42             if($i<=$index)
    43             {              
    44                 $tmp = $curr->next;
    45                 break;
    46             }
    47             $curr = $curr->next;
    48             $i ++;
    49          }
    50          $curr->next=$tmp->next;
    51     }
    52 }
    53 
    54 
    55 $l = new singleLinkedList(); 
    56 $l->addLink (new node(1));
    57 $l->addLink (new node(2));
    58 $l->addLink (new node(3));
    59 $l->addLink (new node(4));
    60 $lists->addLink (new node(5));
    61 $lists->addLink (new node(6));
    62 $lists->delLink ();
    63 print_r($lists->header);die;

  • 相关阅读:
    PAT甲级1018Public Bike Management
    PAT甲级1003Emergency
    android的AIDL
    View的滑动冲突和解决方案
    弹性滑动原理
    View的滑动原理和多种滑动方法
    Android的Activity的生命周期
    Android获取App版本号和版本名
    转:Android检查设备是否联网
    androidstudio实现增量更新步骤
  • 原文地址:https://www.cnblogs.com/zz-952/p/9836506.html
Copyright © 2011-2022 走看看