can we create linked list in php

Solutions on MaxInterview for can we create linked list in php by the best coders in the world

showing results for - "can we create linked list in php"
Claire
30 Oct 2020
1<?php
2//node structure
3class Node {
4public $data;
5public $next;
6}
7class LinkedList {
8public $head;
9public function __construct(){
10$this->head = null;
11}
12
13//Add new element at the end of the list
14public function push_back($newElement) {
15$newNode = new Node();
16$newNode->data = $newElement;
17$newNode->next = null;
18if($this->head == null) {
19$this->head = $newNode;
20} else {
21$temp = new Node();
22$temp = $this->head;
23while($temp->next != null) {
24$temp = $temp->next;
25}
26$temp->next = $newNode;
27}
28}
29//display the content of the list
30public function PrintList() {
31$temp = new Node();
32$temp = $this->head;
33if($temp != null) {
34echo “\nThe list contains: “;
35while($temp != null) {
36echo $temp->data.” “;
37$temp = $temp->next;
38}
39} else {
40echo “\nThe list is empty.”;
41}
42}
43};
44// test the code
45$MyList = new LinkedList();
46//Add three elements at the end of the list.
47$MyList->push_back(10);
48$MyList->push_back(20);
49$MyList->push_back(30);
50$MyList->PrintList();
51//The output of the above code will be:
52//The list contains: 10 20 30
53?>