<?php

class Node 
{    
    public int $data;
    public Node $next;
    
    public function __construct(int $data) {
        $this->data = $data;        
    }
}
class SLList 
{
    public Node $head;
    public Node $tail;
    public int $size;

    public function __construct() {
        $this->size = 0;
    }

    public function __toString() : string {        
        if ($this->size == 0) {
            return "[]\n";
        }
        $output = "[ ";
        $node = $this->head;
        while (isset($node->next)) {
            $output .= $node->data . " -> ";
            $node = $node->next;
        }
        $output .= $node->data . " ]\n";
        return $output;
    }    
   
    public function pushLeft(int $data) {
        $node = new Node($data);
        if (empty($this->head)) {
            $this->tail = $node;
        } else {
            $node->next = $this->head;    
        }
        $this->head = $node; 
        $this->size++;
    }
    
    public function pushRight(int $data) {        
        if ($this->size == 0) {
            self::pushLeft($data);
            return $output;
        }
        $node = new Node($data);
        $this->tail->next = $node;
        $this->tail = $node;
        $this->size++;
    }

    public function popLeft() {        
        if ($this->size == 0) {
            return;
        }
        $output = $this->head->data;
        $this->head = $this->head->next;
        $this->size--;
        return $output;
    }

    public function popRight() {        
        if ($this->size == 0) {
            return;
        }
        if ($this->size == 1) {
            return self::popLeft();
        }
        $node = $this->head;
        while (isset($node->next->next)) {
            $node = $node->next;
        }
        $output = $node->next->data;
        $this->tail = $node;
        unset($node->next);
        $this->size--;
        return $output;
    }    
}

$list = new SLList();
echo $list;
echo $list->popLeft();
echo $list->popRight();
$list->pushLeft(400);
$list->pushLeft(500);
$list->pushRight(300);
$list->pushRight(200);
$list->pushRight(100);
echo $list;
echo $list->popLeft() . "\n";
echo $list;
echo $list->popRight() . "\n";
echo $list;
print_r($list);


Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: