post

The SplStack class

Posted 05 November 2017

Stack is the data structure let you add and remove item Last in  First out order. You can push item on the top and also pop item on the top

PHP SplSatck  is just a inked list , where it can be seen as vertical list, where elements are stack upon each other. SplStack Extends SplDoublyLinkedList and Inherit all methods inside the SplStack . Only different between SplStack and SplDoublyLinkedList you can’t set IT_MODE_FIFO in SplStack::setIteratorMode It will throw RuntimeException

USAGE

use an SplStack where you want to store data and only deal with last element you have stored. it mostly useful for recursive functionality where store all data and deal with them until stack is empty.

Creates calculator with SplStack, Creates Stack and where we push two operators and operations. it only pops the two operators and operation from stack. does the calculation and push in to stack . this process continue until only one item present in stack

$stack = new SplStack();

// This will calculate: (((3 * 4) + 4) - 2) / 2) = 7
$stack->push("divide");
$stack->push(2);
$stack->push("subtract");
$stack->push(2);
$stack->push("add");
$stack->push(4);
$stack->push("multiply");
$stack->push(3);
$stack->push(4);

calculate($stack);

print "The result: " . $stack->pop() . PHP_EOL;
exit;

function calculate(SplStack $stack)
{
    $value1 = $stack->pop();
    $value2 = $stack->pop();
    $cmd = $stack->pop();
   
    // Execute command and push the result back onto the stack
    switch ($cmd) {
        case "add" :
            $stack->push($value1 + $value2);
            break;
        case "subtract" :
            $stack->push($value1 - $value2);
            break;
        case "multiply" :
            $stack->push($value1 * $value2);
            break;
        case "divide" :
            $stack->push($value1 / $value2);
            break;
    }

    // If we still have multiple entries on the stack,
    // so calculate again
    if ($stack->count() > 1) {
        calculate($stack);
    }
}
Leave a Reply

Your email address will not be published. Required fields are marked *