How to write PHP stack

WBOY
Release: 2016-08-08 09:26:23
Original
1085 people have browsed it

Among the interview questions yesterday, there was a question about the application of stack. I knew the principle at that time, but I had not written the specific code. I will write about it today. .

<?php
/*
 * Created on 2015-4-9
 *
 * PHP栈的应用
 */

 class Stack{

 	private $stack_arr =array();
 	private $end = null;

 	public function push($str){

 		if($this->end === null){
 			$this->end = 0;
 		}else{
 			$this->end++;
 		}

 		$this->stack_arr[$this->end] = $str;

 	}

 	public function pop(){
		// if($this->end=null){return false;} //如果这样写,变量end为0的时候,是否就出错了
		if(empty($this->stack_arr)){return false;}
		  $pop_data = $this->stack_arr[$this->end];

		  array_splice($this->stack_arr,$this->end);

		 $this->end--;
		 return $pop_data;
	 	}

	 public function getData(){

	 	return $this->stack_arr;
	 }
 }
$arr = array();

$data_obj =new Stack();
$data_obj->push("1_one");
$data_obj->push("2_two");
$data_obj->push("3_three");
$data_obj->pop();
$arr = $data_obj->getData();
print_r($arr);


?>
Copy after login

Print results:
---------------------------------------- -------------------------------------------------- ---------------------
Array ( [0] => 1_one [1] => 2_two )

The above introduces how to write the PHP stack, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template