用一个数组还存储两个栈。数组有两个端点,两个栈有两个栈底,让一个栈的栈底作为数组的始端,即下标为0处,另一个栈为数组的末端,即下标为数组长度n-1处。这样,两个栈如果增加元素,就是两端点向中间延伸。
关键思路:
它们是在数组的两端,向中间靠拢。top1和top2是栈1和栈2的栈顶指针,只要它们两个不见面,两个栈就可以一直使用。
由此可知,当top1 = -1 时,就是栈1 为空;当top2 = n时,就是栈2为空;当两个指针之间相差1时,即top1 + 1 = top2 两个栈就见面了,此时,就是栈满了。
下面就用php实现两栈共享空间的进栈和出栈操作
<?php header("content-type:text/html;charset=utf-8"); /** * 两栈共享空间的基本操作 * *包括 * 1.栈的初始化 __contruct() * 2.进栈操作 push() * 3.出栈操作 pop() */ class Double_stack{ const MAXSIZE = 10; private $data; private $top1; private $top2; public function __construct() { $this->data = array(); $this->top1 = -1; $this->top2 = self::MAXSIZE; } //进栈操作 push() public function push($elem,$stackNumber){ if($this->top1+1 == $this->top2){ echo "栈已满"; return false; } if($stackNumber == 1){ $this->top1++; $this->data[ $this->top1] = $elem; } if($stackNumber == 2){ $this->top2--; $this->data[ $this->top2] = $elem; } } //出栈操作 pop() public function pop($stackNumber){ if($stackNumber == 1){ if($this->top1 == -1){ echo "栈1已空"; return false; }else{ $value = $this->data[$this->top1]; unset($this->data[$this->top1]); $this->top1--; return $value; } } if($stackNumber == 2){ if($this->top2 == self::MAXSIZE){ echo "栈2已空"; return false; }else{ $value = $this->data[$this->top2]; unset($this->data[$this->top2]); $this->top2++; return $value; } } } } ?>
实现以上函数功能:
<?php header("content-type:text/html;charset=utf-8"); include 'double_stack.class.php'; $double_stack = new Double_stack(); echo "进栈操作:"; echo "</br>"; $double_stack->push(1,1); $double_stack->push(2,2); $double_stack->push(3,2); $double_stack->push(4,1); $double_stack->push(5,2); $double_stack->push(6,2); $double_stack->push(7,1); $double_stack->push(8,2); $double_stack->push(9,2); $double_stack->push(10,1); print_r($double_stack); echo "</br>"; echo "</br>"; echo "进栈操作,直至栈满:"; echo "</br>"; $double_stack->push(666,1); echo "</br>"; $double_stack->push(888,2); echo "</br>"; echo "</br>"; echo "出栈操作:"; echo "</br>"; echo "(1)、栈1出栈,top1-1,同时栈1的栈顶元素10被销毁"; echo "</br>"; $double_stack->pop(1); print_r($double_stack); echo "</br>"; echo "直至栈1空:"; echo "</br>"; $double_stack->pop(1); $double_stack->pop(1); $double_stack->pop(1); $double_stack->pop(1); echo "</br>"; echo "(2)、栈2出栈,top2+1,同时栈2的栈顶元素9被销毁"; echo "</br>"; $double_stack->pop(2); print_r($double_stack); echo "</br>"; echo "直至栈2空:"; echo "</br>"; $double_stack->pop(2); $double_stack->pop(2); $double_stack->pop(2); $double_stack->pop(2); $double_stack->pop(2); $double_stack->pop(2);
最后输出的结果: