Skip to content

Instantly share code, notes, and snippets.

@pipethedev
Created May 10, 2020 19:38
Show Gist options
  • Select an option

  • Save pipethedev/1f1b33c8d2ac295942808a113daecb4f to your computer and use it in GitHub Desktop.

Select an option

Save pipethedev/1f1b33c8d2ac295942808a113daecb4f to your computer and use it in GitHub Desktop.
<?PHP
class Node {
public $data;
public $next;
public $br = '<br>';
public function __construct($data, $next = null){
$this->data = $data;
$this->next = $next;
}
}
class LinkedList {
public $head;
public $size;
public function __construct(){
$this->head = null;
$this->size = 0;
}
public function insertFirst($data){
$this->head = new Node($data, $this->head);
$this->size++;
}
public function insertAt($data, $index){
if($index > 0 && $index > $this->size){
return ;
}
if($index === 0 ){
$this->insertFirst($data);
}
$node = new Node($data);
$current;
$previous;
$current = $this->head;
$count = 0;
while ($count < $index) {
$previous = $current;
$count++;
$current = $current->next;
}
$node->next = $current;
$previous->next = $node;
$this->size++;
}
public function removeAt($index){
if($index > 0 && $index > $this->size ){
return;
}
$current = $this->head;
$previous;
$count = 0;
if($index === 0){
$this->head = $current->next;
}else{
while($count < $index){
$count++;
$previous = $current;
$current = $current->next;
}
$previous->next = $current->next;
}
$this->size--;
}
public function insertLast($data){
$node = new Node($data);
// $current;
if(!$this->head){
$this->head = $node;
}else{
$current = $this->head;
while ($current->next) {
$current = $current->next;
}
$current->next = $node;
}
$this->size++;
}
public function getAt($index){
$current = $this->head;
$count = 0;
while ($current) {
if($count == $index){
print_r($current->data);
}
$count++;
$current = $current->next;
}
return null;
}
public function clearList(){
$this->head = null;
$this->size = 0;
}
public function printListData(){
$current = $this->head;
while($current){
echo $current->data;
$current = $current->next;
}
}
}
$ll = new LinkedList();
$ll->insertFirst();
$ll->insertFirst();
$ll->insertFirst();
$ll->insertLast();
$ll->insertAt();
$ll->getAt();
$ll->removeAt();
$ll->clearList();
$ll->printListData();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment