链接列表不保存数据库

时间:2013-01-05 21:43:41

标签: php data-structures web linked-list

使用PHP 5.3.10,我创建了一个链接列表类,我正在尝试保存一个足球运动员列表。

调用add函数后,对象似乎永远不会保留任何信息。 var_dump($playerList)为我的头部和尾部指针返回NULL。或者,如果我将其替换为var_dump($playerList->count),则无论我在何处放置var_dump计数语句,它都不会打印任何内容。

我已浏览过手册,但在语法中找不到错误。我的直觉告诉我mysql_fetch_array正在做一些时髦的事情。如下所述,我的测试表明,当我调用playerList->add()时,值实际上是传递的。无论如何,这是我的简单代码:

/* Populates lists with available players. */
function populateList($sql)
{
    $playerList = new PlayerList();
    while ($row = mysql_fetch_array($sql, MYSQL_NUM)) 
    {
        $playerList->add(new Player($row[0], $row[1], $row[2], $row[3], $row[4]));
    }
    var_dump($playerList);
}

我的链表类:

include 'PlayerNode.php';

class PlayerList
{
    public $head;
    public $tail;
    public $count;

    function PlayerList()
    {
        $head = null;
        $tail = null;
        $count = 0;
    }

    function add($player)
    {
        $count ++;            
        $node = new PlayerNode($player);

        //First time in
        if ($head == null)
        {
            $head = $node;
            $tail = $node;
            $head->nextPtr = null;
        }
        // All other times
        else
        {
            $tail->nextPtr = $node;
            $tail = $node;
            $node->nextPtr = null;
        }
        $count++;
    }               
}

我可以在链表类中放置var_dump($node)和echo语句,并观察PlayerNode是否正常工作。

但是,另一个奇怪的观察...... if($head==null)总是评价为真。这可能是相关的吗?

1 个答案:

答案 0 :(得分:1)

插入单一链接列表的头部:     我们可以轻松地将元素插入列表的头部。那我们怎么做呢?创建一个新节点,将新节点的下一个点设置为当前头节点,并将head变量(在类中)指向新节点。即使链接列表为空,此方法也有效。请注意,在我们发送head变量指向新节点之前,我们将新节点的下一个点设置为head节点。

插入单一链接列表的尾部:     我们还可以轻松地在链接列表的尾部插入元素,前提是我们保留链接列表的尾节点的引用。创建一个新节点,将新节点的下一个节点设置为null,将尾节点的下一个节点指向新节点,将tail变量设置为指向新元素。注意我们在将tail变量更改为指向新节点之前设置了前一个尾节点的下一个节点。

在所有其他时间,将新节点添加到头部或尾部。

              // All other times if head
                else{
                        $temp = $head;
                        $head = $node;
                        $node->nextPtr = $temp;
                        count ++; 
                    }
相关问题