PHP数据结构之:栈(Stack)

这几天复习数据结构的时候,想到用PHP来实现3种数据结构.本文介绍2种实现栈(stack)的方法.

栈和队列比较明显的区别在于队列是先进先出,即 FIFO,而栈是后进先出LIFO

1.使用最基本的array_pop 以及 array_push 实现

PS:下例中实现了SPL一个COUNTABLE的接口.

<?php

class StackDemo implements Countable
{

	private $stack = array();
	
	//countable 
	public function count(){
		return count( $this->stack );
	}

	//func to check statck is empty
	public function isEmpty(){
		return 0 === count($this->stack) ;
	}
	
	//push
	public function push( $val ){
		return array_push($this->stack,$val);
	}
	
	//pop 
	public function pop(){
		return array_pop($this->stack);
	}
}


$stack = new StackDemo;

$stack->push('hello');
$stack->push('roban');
$stack->push('lee');

echo 'Before pop:'.count($stack), PHP_EOL ;
echo 'Poped:',$stack->pop(), PHP_EOL ;
echo 'After pop:',count($stack) , PHP_EOL ;

2. 使用SPLStack类实现:


<?php

$stack = new SplStack();

$stack->push('hello');
$stack->push('roban');
$stack->push('lee');

echo 'Before pop:'.count($stack), PHP_EOL ;
echo 'Poped:',$stack->pop(), PHP_EOL ;
echo 'After pop:',count($stack) , PHP_EOL ;


你可能感兴趣的:(数据结构,PHP,PHP,栈,栈)