in reply to Re^7: [OT:] Is this Curriculum right?
in thread [OT:] Is this Curriculum right?
The kid performed - somehow:
#!/usr/bin/env php <?php class Node { public $data; public $next; } class LinkedList { public $head; public function __construct(){ $this->head = null; } public function push_back($newElement) { $newNode = new Node(); $newNode->data = $newElement; $newNode->next = null; if($this->head == null) { $this->head = $newNode; } else { $temp = new Node(); $temp = $this->head; while($temp->next != null) { $temp = $temp->next; } $temp->next = $newNode; } } public function push_at($newElement, $position) { $newNode = new Node(); $newNode->data = $newElement; $newNode->next = null; if($position < 1) { echo "\nposition should be >= 1."; } else if ($position == 1) { $newNode->next = $this->head; $this->head = $newNode; } else { $temp = new Node(); $temp = $this->head; for($i = 1; $i < $position-1; $i++) { if($temp != null) { $temp = $temp->next; } } if($temp != null) { $newNode->next = $temp->next; $temp->next = $newNode; } else { echo "\nThe previous node is null."; } } } public function PrintList() { $temp = new Node(); $temp = $this->head; if($temp != null) { echo "The list contains: "; while($temp != null) { echo $temp->data." "; $temp = $temp->next; } echo "\n"; } else { echo "The list is empty.\n"; } } }; $MyList = new LinkedList(); $MyList->push_back(10); $MyList->push_back(20); $MyList->push_back(30); $MyList->PrintList(); $MyList->push_at(100, 2); $MyList->PrintList(); $MyList->push_at(200, 1); $MyList->PrintList(); ?>
See also. Regards, Karl
«The Crux of the Biscuit is the Apostrophe»
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^9: [OT:] Is this Curriculum right?
by Marshall (Canon) on Dec 06, 2021 at 19:31 UTC | |
by karlgoethebier (Abbot) on Dec 09, 2021 at 11:05 UTC | |
by Marshall (Canon) on Dec 13, 2021 at 02:04 UTC | |
by karlgoethebier (Abbot) on Dec 16, 2021 at 12:07 UTC |