How can PHP be used to dynamically update the order of items in a link list based on user input?
To dynamically update the order of items in a linked list based on user input in PHP, you can create a form where users can input the new order of items. Upon form submission, you can update the linked list structure accordingly by reordering the nodes based on the user's input.
<?php
class Node {
public $data;
public $next;
function __construct($data) {
$this->data = $data;
$this->next = null;
}
}
class LinkedList {
public $head;
function __construct() {
$this->head = null;
}
function insert($data) {
$newNode = new Node($data);
$newNode->next = $this->head;
$this->head = $newNode;
}
function display() {
$current = $this->head;
while ($current != null) {
echo $current->data . " ";
$current = $current->next;
}
}
function updateOrder($newOrder) {
$current = $this->head;
$index = 0;
while ($current != null) {
$current->data = $newOrder[$index];
$current = $current->next;
$index++;
}
}
}
// Create a linked list
$linkedList = new LinkedList();
$linkedList->insert(1);
$linkedList->insert(2);
$linkedList->insert(3);
// Display the current order
echo "Current order: ";
$linkedList->display();
echo "<br>";
// User input for new order
$newOrder = [3, 1, 2];
// Update the order based on user input
$linkedList->updateOrder($newOrder);
// Display the updated order
echo "Updated order: ";
$linkedList->display();
?>