本文实例讲述了php实现的顺序线性表。分享给大家供大家参考,具体如下:

<?php
/*
 * 线性顺序表 ,其是按照顺序在内存进行存储,出起始和结尾以外都是一一连接的(一般都是用一维数组的形式表现)
 *
 * getelem: 返回线性表中第$index个数据元素
 * listlength: 返回线性表的长度
 * locateelem: 返回给定的数据元素在线性表中的位置
 * priorelem: 返回指定元素的前一个元素
 * nextelem: 返回指定元素的后一个元素
 * listinsert: 在第index的位置插入元素elem
 * listdelete: 删除第index位置的元素elem
 */
class sequence {
  public $seqarr;
  public $length;
  public function __construct($arr) {
    $this->seqarr = $arr;
    $this->length = count($arr);
  }
  /*
   * 返回线性表中第$index个数据元素
   */
  public function getelem($index) {
    if (($this->length) == 0 || $index < 0 || ($index > $this->length)) {
      return "error";
    }
    return $this->seqarr[$index - 1];
  }
  /*
   * 返回线性表的长度
   *
   */
  public function listlength() {
    return $this->length;
  }
  /*
   * 返回给定的数据元素在线性表中的位置
   */
  public function locateelem($elem) {
    for ($i = 0; $i < ($this->length); $i++) {
      if (($this->seqarr[$i]) == $elem) {
        return $i + 1;
      }
    }
  }
  /*
   * priorelem: 返回指定元素的前一个元素
   */
  public function priorelem($elem) {
    for ($i = 0; $i < ($this->length); $i++) {
      if (($this->seqarr[$i]) == $elem) {
        if ($i == 0) {
          return "error (is null) ";
        } else {
          return $this->seqarr[$i - 1];
        }
      }
    }
  }
  /*
   * nextelem: 返回指定元素的后一个元素
   */
  public function nextelem($elem) {
    for ($i = 0; $i < ($this->length); $i++) {
      if (($this->seqarr[$i]) == $elem) {
        return $this->seqarr[$i + 1];
      }
    }
  }
  /*
   * listinsert: 在第index的位置插入元素elem
   */
  public function listinsert($index, $elem) {
    if (($this->length) == 0 || $index < 0 || $index > ($this->length)) {
      return "error";
    }
    for ($i = $index; $i < ($this->length); $i++) {
      $this->seqarr[$i + 1] = $this->seqarr[$i];
    }
    $this->seqarr[$index] = $elem;
    $this->length = $this->length + 1;
    return $this->seqarr;
  }
  /*
   * listdelete: 删除第index位置的元素
   */
  public function listdelete($index) {
    if (($this->length) == 0 || $index < 0 || $index > ($this->length - 1)) {
      return "error";
    }
    unset($this->seqarr[$index]);
    $this->length--;
    return $this->seqarr;
  }
}
?>

更多关于php相关内容感兴趣的读者可查看本站专题:《php数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《php数组(array)操作技巧大全》、《php常用遍历算法与技巧总结》及《php数学运算技巧总结》

希望本文所述对大家php程序设计有所帮助。