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»
In reply to Re^8: [OT:] Is this Curriculum right?
by karlgoethebier
in thread [OT:] Is this Curriculum right?
by karlgoethebier
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |