<?php
/*
*
* @Author: Zuhair Mirza
* @First Implementation Of Stack Class and Pointer Approach
* @Date : 30-July-2013
*
*/
$s = new Stack();
$s->push(1);
$s->push(2);
$s->push(3);
// 3 2 1
echo $s;
$s->pop();
$s->pop();
// 1
echo $s;
class Struct {
protected $_data = null;
protected $_next = null;
public function __construct($data, $next) {
$this->_data = $data;
$this->_next = $next;
}
public function getData() {
return $this->_data;
}
public function setData(&$data) {
$this->_data = $data;
}
public function getNext() {
return $this->_next;
}
public function setNext(&$next) {
$this->_next = $next;
}
}
class Stack {
protected $_top = null;
public function push($data) {
$item = new Struct($data, null);
if ($this->_top == null) {
$this->_top = $item;
} else {
$item->setNext($this->_top);
$this->_top = $item;
}
}
public function pop() {
if ($this->_top) {
$t = $this->_top;
$data = $t->getData();
$this->_top = $this->_top->getNext();
$t = null;
return $data;
}
}
public function __toString() {
$output = '';
$t = $this->_top;
while ($t) {
$output .= $t->getData() . ' ';
$t = $t->getNext();
}
return $output;
}
}
/*
* ----------------------THE END-----------------------
*/
?>
/*
*
* @Author: Zuhair Mirza
* @First Implementation Of Stack Class and Pointer Approach
* @Date : 30-July-2013
*
*/
$s = new Stack();
$s->push(1);
$s->push(2);
$s->push(3);
// 3 2 1
echo $s;
$s->pop();
$s->pop();
// 1
echo $s;
class Struct {
protected $_data = null;
protected $_next = null;
public function __construct($data, $next) {
$this->_data = $data;
$this->_next = $next;
}
public function getData() {
return $this->_data;
}
public function setData(&$data) {
$this->_data = $data;
}
public function getNext() {
return $this->_next;
}
public function setNext(&$next) {
$this->_next = $next;
}
}
class Stack {
protected $_top = null;
public function push($data) {
$item = new Struct($data, null);
if ($this->_top == null) {
$this->_top = $item;
} else {
$item->setNext($this->_top);
$this->_top = $item;
}
}
public function pop() {
if ($this->_top) {
$t = $this->_top;
$data = $t->getData();
$this->_top = $this->_top->getNext();
$t = null;
return $data;
}
}
public function __toString() {
$output = '';
$t = $this->_top;
while ($t) {
$output .= $t->getData() . ' ';
$t = $t->getNext();
}
return $output;
}
}
/*
* ----------------------THE END-----------------------
*/
?>
No comments:
Post a Comment