How to use unset() for this Linear Linked List in PHP

Posted by Peter on Stack Overflow See other posts from Stack Overflow or by Peter
Published on 2010-06-12T04:56:39Z Indexed on 2010/06/12 5:02 UTC
Read the original article Hit count: 190

Filed under:
|
|

I'm writing a simple linear linked list implementation in PHP. This is basically just for practice... part of a Project Euler problem. I'm not sure if I should be using unset() to help in garbage collection in order to avoid memory leaks. Should I include an unset() for head and temp in the destructor of LLL?

I understand that I'll use unset() to delete nodes when I want, but is unset() necessary for general clean up at any point?

Is the memory map freed once the script terminates even if you don't use unset()?

I saw this SO question, but I'm still a little unclear. Is the answer that you simply don't have to use unset() to avoid any sort of memory leaks associated with creating references?

I'm using PHP 5.. btw.

Unsetting references in PHP

PHP references tutorial

Here is the code - I'm creating references when I create $temp and $this->head at certain points in the LLL class:

class Node
{
    public $data;
    public $next;
}
class LLL
{
    // The first node
    private $head;
    public function __construct()
    {
        $this->head = NULL;
    }
    public function insertFirst($data)
    {
        if (!$this->head)
        {
            // Create the head
            $this->head = new Node;
            $temp =& $this->head;
            $temp->data = $data;
            $temp->next = NULL;                     
        } else
        {
            // Add a node, and make it the new head.
            $temp = new Node;        
            $temp->next = $this->head;
            $temp->data = $data;
            $this->head =& $temp;
        }
    }
    public function showAll()
    {
        echo "The linear linked list:<br/>&nbsp;&nbsp;";
        if ($this->head)
        {               
            $temp =& $this->head;
            do
            {
                echo $temp->data . " ";
            } while ($temp =& $temp->next);
        } else
        {
            echo "is empty.";
        }
        echo "<br/>";
    }
}

Thanks!

© Stack Overflow or respective owner

Related posts about php

Related posts about references