|
<? /* name : linkedlist.php
* author : panji (panji6887@yahoo.com)
* purpose : make the abstract data type of linked list
* date : 2006/06/22
*/
//define the struct node list class ADTlist{
var $fill;
var $next;
} //type and operation definition of linkedlist class linkedlist{
var $firstPointer;
var $lastPointer;
//list initialization
//make the first and last pointer of list
function linkedlist($e=''){
$this->firstPointer = $this->factorylist();
$this->lastPointer = $this->factorylist();
$this->firstPointer->next = null;
$this->firstPointer->fill = $e;
$this->lastPointer = $this->firstPointer;
}
//inserting data before first element of list
function insertfirst($e){
$help= $this->factorylist();
$help->fill = $e;
$help->next = $this->firstPointer;
$this->firstPointer = $help;
}
//inserting data after last element of list
function insertlast($e){
$help= $this->factorylist();
$help->fill = $e;
$help->next = null;
$this->lastPointer->next = $help;
$this->lastPointer = $help;
}
//deleting data in the first position of list
function deletefirst(){
$this->firstPointer = $this->firstPointer->next;
}
//deleting data in the last position of list
function deletelast(){
$help=$this->factorylist();
$help=$this->firstPointer;
while($help->next!=$this->lastPointer && $help->next!=null){
$help=$help->next;
}
$this->lastPointer=$help;
$this->lastPointer->next=null;
}
// returning the Linkedlist struct
function factorylist(){
return new ADTlist();
}
// to write all list element
function writelist(){
$help = $this->firstPointer;
while($help->fill!=null && $help->fill!=null){
echo" ".$help->fill." -> ";
$help = $help->next;
}
echo"nil";
}
} //example $list = new linkedlist(); $list->insertfirst('panji'); $list->insertfirst('agus'); $list->insertfirst('mutt'); $list->insertlast('aqin'); $list->insertlast('ganteng'); $list->insertlast('sekali'); $list->insertfirst('test1');
$list->insertfirst('test2'); $list->deletelast(); $list->deletefirst();
$list->deletelast(); $list->writelist(); ?>
|
|
|
Usage Example
|
<?
$list = new linkedlist();
$list->insertfirst('panji'); $list->insertfirst('agus'); $list->insertfirst('mutt'); $list->insertlast('aqin'); $list->insertlast('ganteng');
$list->insertlast('sekali'); $list->insertfirst('test1'); $list->insertfirst('test2');
$list->deletelast(); $list->deletefirst(); $list->deletelast(); $list->writelist();
?>
|
|
|
Rate This Script
|
|