<?php /** 1. DestroyStack(): 栈的销毁 2. ClearStack(): 将栈置为空栈 3. StackEmpty(): 判断栈是否为空 4. StackLength(): 返回栈的长度 5. GetTop(): 取得栈顶的元素 6. Push(): 插入新的栈顶元素 7. Pop(): 删除栈顶元素 8. StackTraverse(): 遍历栈元素 */ class LNode{ public $data; public $next; public function __construct($data=null){ $this->data=$data; $this->next=null; } } class LinkStack{ private $top;//用于指向栈顶结点,也就是第一个结点。它相当于头指针。 private $length;//用于指定链栈的长度 public function __construct(){ $this->top=null; $this->length=0; } //销毁链栈 public function DestroyStack(){ while($this->top){ $p=$this->top->next; unset($this->top); $this->top=$p; } $this->length=0; } //清空链栈 public function ClearStack(){ $p=$this->top; while($p){ $q=$p->next; unset($p); $p=$q; } $this->top=null; $this->length=0; } //链栈是否为空 public function StackEmpty(){ if($this->top==null){ return ‘Null‘; }else{ return ‘NO Null‘; } } //链栈的长度 public function StackLength(){ return $this->length; } //取得栈顶的元素 public function GetTop(){ if($this->top!=null){ return $this->top->data; } } //插入新的栈顶结点 public function Push(){ $node=new LNode(mt_rand(10,20)); $node->next=$this->top; $this->top=$node; $this->length++; } //删除栈顶元素 public function Pop(){ if($this->top!=null){ $p=$this->top->next; unset($this->top); $this->top=$p; $this->length--; } } //遍历栈元素 public function StackTraverse(){ $arr=array(); if($this->top !=null){ $p=$this->top; while($p){ $arr[]=$p->data; $p=$p->next; } } return $arr; } }
时间: 2024-10-11 10:56:36