1 PHP实现线性表相关操作

<?php

/**
 * 线性表相关操作
 */
class ListOperation
{
	public $list = null;

	public function __construct() {
		$this->list = array();
	}
	
	// 初始化线性表
	public function InitList($len) {
		$this->list = array_fill(0, $len, 0);//在C中 这里应该通过申请内存并赋值来实现
	}

	// 判断给定的链表是否为空
	public function ListEmpty() {
		return empty($this->list);
	}

	// 清空链表
	public function ClearList() {
		$this->list = array();//在C中这里应该释放内存资源
	}

	// 返回表长
	public function ListLength() {
		return count($this->list);
	}

	// 获取指定元素
	public function GetElem($index, $e) {
		$e = $this->list[$index];
	}

	// 在链表中查找指定元素的位置
	public function LocateElem($target) {
		foreach ($this->list as $key => $value) {
			if ($value == $target) {
				return $key;
			}
		}

		return -1;
	}

	// 在链表中指定位置插入新元素
	public function ListInsert($index, $value) {

		// 判断范围
		if ($index < 0 || $index > $this->ListLength($this->list)) {
			return false;
		}

		if ($index == 0) {
			array_unshift($this->list, $value);
			return true;
		}

		if ($index == $this->ListLength($this->list)) {
			array_push($this->list, $value);
			return true;
		}

		for ($i=$this->ListLength($this->list) - 1; $i >= $index - 1; $i--) { 
			$this->list[$i + 1] = $this->list[$i]; //将前面的元素向后移动
		}

		$this->list[$index] = $value;
		return true;
	}

	// 删除第i个位置元素 并用deleteValue返回其值
	public function ListDelete($index, &$deleteValue) {

		if ($index < 0 || $index > $this->ListLength($this->list)) {
			return;
		}

		if ($index == $this->ListLength($this->list) - 1) {
			unset($this->list[$index]);
			return true;
		}


		$deleteValue = $this->list[$index];
		for ($i=$index; $i < $this->ListLength($this->list) - 1; $i++) { 
			$this->list[$i] = $this->list[$i + 1]; // 全部向前移动一个位置
		}

		unset($this->list[$this->ListLength($this->list) - 1]);//删除后面多余的一个元素 使得链表整体长度减一

		return $deleteValue;
	}
}

$listObj = new ListOperation();
$listObj->InitList(10);
print_r($listObj->ListInsert(3, 44));
print_r($listObj->ListInsert(4, 33));
print_r($listObj->ListInsert(0, 1));
print_r($listObj->ListDelete(5, $deleteValue));
print_r($listObj->list);
print_r($deleteValue);

线性表的优缺点

优点

因为线性表使用的是连续的内存空间,所以存(改)和读的时间复杂度为O(1),适合存储数量固定的内容

如果插入和删除的元素为表中最后一个位置,那么时间复杂度仍然为O(1)

缺点

插入和删除的时间复杂度为O(n),不适合存储频繁删除和插入的内容

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值