0
I have the following statement
- Define a stored stack in an array; a. Insert a widget at the top of the stack (push); b. Removing an item from the top of the stack (pop); c. Return the number of stack elements (elementsNumbers);
- Write functions for: a. Insert an element in the eleventh position of the stack; b. Remove an element from the ith stack position;
The whole item 1 I already finished in PHP with the STACK class however now is the monster, because how will I be able to access the ith position of the stack? which in this case is item 2
Code:
<?php
class Stack
{
protected $stack;
protected $size;
public function __construct($size = 50) {
//Initialize stack
$this->stack = array();
//Initialize stack size
$this->size = $size;
}
/**
* Insert an element in a stack
* @param type $data
*/
public function push($data) {
//Check stack overflow
if(count($this->stack) < $this->size) {
//Inserts an element at the beginning
array_unshift($this->stack, $data);
} else {
// If stack is full then throw stack overflow exception
throw new RuntimeException("Stack overflow");
}
}
/**
* Removes an element from a stack
*
*/
public function pop() {
// If stack is empty
if (empty($this->stack)) {
throw new RuntimeException("Stack underflow");
} else {
return array_shift($this->stack);
}
}
}
$stack = new Stack();
$stack->push(4);
$stack->push(5);
echo $stack->pop(); // Pop 5
$stack->push(7);
$stack->push(9);
$stack->push(8);
echo $stack->pop(); // Pop 8
echo $stack->pop(); // Pop 9
What have you tried?
– Luiz Felipe