php中的LinkedList [重复]

Possible Duplicate:
Implement linked list in php

We can make link list in Java, C++ because C++ has pointers and in Java can define objects like TempClass t = new TempClass();.

How can I make a linked list in PHP?

The Standard PHP Library (SPL - here) offers some implementations. Besides that - googling as simple as "Linked list php" does get you some acceptable results!

Here is how to create a LinkedList in PHP.

It is the same idea as C# or Java.

You need to have a Node class defined and you need to wrap that in a linked list class.

Here is a full example: http://www.codediesel.com/php/linked-list-in-php/

Basic Linked List example in 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;
    }
    public function insert($data){
        $link = new Node($data);
        $link->next = $this->head;
        $this->head= &$link;
    }
}

$m = new LinkedList();
$m->insert(2);
$m->insert(3);
$m->insert(4);

echo $m->head->data;              //prints 4
echo $m->head->next->data;        //prints 3
echo $m->head->next->next->data;  //prints 2

?>

How to internally verbalize what is going on above:

A new PHP class called Node is created with member variables $data and $next. $data holds the information contained in each link of the linked list. $next has the address of the next Node in the list.

A LinkedList class wraps a collection of linked Nodes. The member variable $head points to the first Node in the linked list. The method insert creates a new Node in memory. The new node has its next reference point to the old head. Then head is made to reference the newly created node. Thus this linked list represents a stack, like a stack of books.