Created
June 24, 2010 10:29
-
-
Save TechZi/451291 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Link { | |
public $key; | |
public $value; | |
public $next = null; | |
public function __construct($key, $value) { | |
$this->key = $key; | |
$this->value = $value; | |
} | |
public function displayLink() { | |
echo '{'.$this->key.' : '.$this->value.'} '; | |
} | |
} | |
class LinkList { | |
private $first = null; | |
public function isEmpty() { | |
return empty($this->first); | |
} | |
public function insertFirst($key, $value) { | |
$link = new Link($key, $value); | |
if (!$this->isEmpty()) { | |
$link->next = $this->first; | |
} | |
$this->first = $link; | |
} | |
public function deleteFirst() { | |
if ($this->isEmpty()) { | |
return null; | |
} | |
$this->first = $this->first->next; | |
return $this->first; | |
} | |
public function displayList() { | |
if ($this->isEmpty()) { | |
echo 'LinkList is null'; | |
return ; | |
} | |
$current = $this->first; | |
while ($current !== null) { | |
$current->displayLink(); | |
$current = $current->next; | |
} | |
} | |
public function find($key) { | |
if ($this->isEmpty()) { | |
echo 'LinkList is null'; | |
return ; | |
} | |
$current = $this->first; | |
while ($current !== null) { | |
if ($current->key == $key) { | |
return $current; | |
} else { | |
$current = $current.next; | |
} | |
} | |
return null; | |
} | |
public function delete($key) { | |
$current = $this->first; | |
$previous = $this->first; | |
while ($current->key != $key) { | |
if ($current->next == null) { | |
return null; | |
} else { | |
$previous = $current; | |
$current = $current->next; | |
} | |
} | |
if ($current == $this->first) { | |
$this->first = $this->first->next; | |
} else { | |
$previous->next = $current->next; | |
} | |
return current; | |
} | |
} | |
$linkList = new LinkList(); | |
$linkList->insertFirst(1, 1.99); | |
$linkList->insertFirst(2, 2.99); | |
$linkList->insertFirst(3, 3.99); | |
$linkList->insertFirst(4, 4.99); | |
$linkList->displayList(); | |
echo "\n"; | |
//$linkList->deleteFirst(); | |
//$linkList->displayList(); | |
//echo "\n"; | |
//$linkList->deleteFirst(); | |
//$linkList->displayList(); | |
//$linkList->find(4)->displayLink(); | |
//$linkList->find(5)->displayLink(); | |
$linkList->delete(4); | |
$linkList->displayList(); | |
echo "\n"; | |
$linkList->delete(3); | |
$linkList->displayList(); | |
echo "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment