Welcome, guest | Sign In | My Account | Store | Cart

Implementation of a single linked list in PHP with Unit Test

PHP, 293 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
<?php

/** 
* Title: Single linked list
* Description: Implementation of a single linked list in PHP 
* @author Sameer Borate | codediesel.com
* @version 1.0 20th June 2008
*/

class ListNode
{
    /* Data to hold */
    public $data;
    
    /* Link to next node */
    public $next;
    
    
    /* Node constructor */
    function __construct($data)
    {
        $this->data = $data;
        $this->next = NULL;
    }
    
    function readNode()
    {
        return $this->data;
    }
}


class LinkList
{
    /* Link to the first node in the list */
    private $firstNode;
    
    /* Link to the last node in the list */
    private $lastNode;
    
    /* Total nodes in the list */
    private static $count;
    
    
    
    /* List constructor */
    function __construct()
    {
        $this->firstNode = NULL;
        $this->lastNode = NULL;
        self::$count = 0;
    }

    public function isEmpty()
    {
        return ($this->firstNode == NULL);
    }
    
    public function insertFirst($data)
    {
        $link = new ListNode($data);
        $link->next = $this->firstNode;
        $this->firstNode = &$link;
        
        /* If this is the first node inserted in the list
           then set the lastNode pointer to it.
        */
        if($this->lastNode == NULL)
            $this->lastNode = &$link;
            
        self::$count++;
    }
    
    public function insertLast($data)
    {
        if($this->firstNode != NULL)
        {
            $link = new ListNode($data);
            $this->lastNode->next = $link;
            $link->next = NULL;
            $this->lastNode = &$link;
            self::$count++;
        }
        else
        {
            $this->insertFirst($data);
        }
    }
    
    public function deleteFirstNode()
    {
        $temp = $this->firstNode;
        $this->firstNode = $this->firstNode->next;
        if($this->firstNode != NULL)
            self::$count--;
            
        return $temp;
    }
    
    public function deleteLastNode()
    {
        if($this->firstNode != NULL)
        {
            if($this->firstNode->next == NULL)
            {
                $this->firstNode = NULL;
                self::$count--;
            }
            else
            {
                $previousNode = $this->firstNode;
                $currentNode = $this->firstNode->next;
                
                while($currentNode->next != NULL)
                {
                    $previousNode = $currentNode;
                    $currentNode = $currentNode->next;
                }
                
                $previousNode->next = NULL;
                self::$count--;
            }
        }
    }
    
    public function deleteNode($key)
    {
        $current = $this->firstNode;
        $previous = $this->firstNode;
        
        while($current->data != $key)
        {
            if($current->next == NULL)
                return NULL;
            else
            {
                $previous = $current;
                $current = $current->next;
            }
        }
        
        if($current == $this->firstNode)
            $this->firstNode = $this->firstNode->next;
        else
            $previous->next = $current->next;
            
        self::$count--;   
    }
    
    public function find($key)
    {
        $current = $this->firstNode;
        while($current->data != $key)
        {
            if($current->next == NULL)
                return null;
            else
                $current = $current->next;
        }
        return $current;
    }
    
    public function readNode($nodePos)
    {
        if($nodePos <= self::$count)
        {
            $current = $this->firstNode;
            $pos = 1;
            while($pos != $nodePos)
            {
                if($current->next == NULL)
                    return null;
                else
                    $current = $current->next;
                    
                $pos++;
            }
            return $current->data;
        }
        else
            return NULL;
    }
    
    public function totalNodes()
    {
        return self::$count;
    }
    
    public function readList()
    {
        $listData = array();
        $current = $this->firstNode;
        
        while($current != NULL)
        {
            array_push($listData, $current->readNode());
            $current = $current->next;
        }
        return $listData;
    }
    
    public function reverseList()
    {
        if($this->firstNode != NULL)
        {
            if($this->firstNode->next != NULL)
            {
                $current = $this->firstNode;
                $new = NULL;
                
                while ($current != NULL)
                {
                    $temp = $current->next;
                    $current->next = $new;
                    $new = $current;
                    $current = $temp;
                }
                $this->firstNode = $new;
            }
        }
    }
}

?>


Test Case

<?php

require_once 'linklist.class.php';
require_once 'PHPUnit/Framework.php';

class LinkListTest extends PHPUnit_Framework_TestCase
{
    public function testLinkList()
    {
        
        $totalNodes = 100;
        
        $theList = new LinkList();
    
        for($i=1; $i <= $totalNodes; $i++)
        {
            $theList->insertLast($i);
        }
        
        $this->assertEquals($totalNodes, $theList->totalNodes());
        
        for($i=1; $i <= $totalNodes; $i++)
        {
            $theList->insertFirst($i);
        }
	
        $totalNodes = $totalNodes * 2;
        $this->assertEquals($totalNodes, $theList->totalNodes());
        
        $theList->reverseList();
        $this->assertEquals($totalNodes, $theList->totalNodes());
        
        $theList->deleteFirstNode();
        $this->assertEquals($totalNodes - 1, $theList->totalNodes());
        
        $theList->deleteLastNode();
        $this->assertEquals($totalNodes - 2, $theList->totalNodes());
        
        /* Delete node which has a value of '5' */
        $theList->deleteNode(5);
        $this->assertEquals($totalNodes - 3, $theList->totalNodes());
        
        /* Insert a node at the end of the list with a value of '22' */
        $theList->insertLast(22);
        $this->assertEquals($totalNodes - 2, $theList->totalNodes());
        
        /* Find a node with a value of '25' (is in the list) */
        $found = $theList->find(25);
        $this->assertEquals(25, $found->data);

        /* Find a node with a value of '125' (is not in the list) */
        $found = $theList->find(125);
        $this->assertNull($found);
        
        /* Return the data stored in the node at position '50' */
        $data = $theList->readNode(50);
        $this->assertEquals(50, $data);
        
        /* Return the data stored in the node at position '450' */
        $data = $theList->readNode(450);
        $this->assertNull($data);
    }
}

?>

4 comments

piccoloprincipeazzurro 15 years, 7 months ago  # | flag

Nice, but php already has arrays. :|

Michal Kočárek 15 years, 6 months ago  # | flag

Why so much OOP?

// Create new linked list: $list = array();

// Append item... array_push($list, $item); // ...to end of the list array_unshift($list, $item); // ...to begin of the list

// Remove... $item = array_pop($list); // ...last item from the list $item = array_shift($list); // ...first item from the list unset($list[array_search($item, $list)]); // ...specific value unset($list[$i]); $list = array_values($list); // ...specific index

I really do not understand, how this could speed up development/resulting script nor make code more readable...

Stanley Tweedle 15 years, 5 months ago  # | flag

Gleaning the sample, I first thought to myself, "Wow-- the author shows an exemplary effort in commenting the PHP!".

Further study intrigued me, however wrinkled the brow, for in reckoning some sensible, well structured architecture, I found myself frustrated to learn I'd read the whole bit, but left without realizing the epiphany I felt so sure I might find there.

considering the existing user-feedback, I'm a bit vexed-- wishing to take a closer look at both the sample, and comment #2.

In my experience, the several suggested analogous, built-in functions are some of the greatest tools of PHP. A thorough review of PHP array Functions-- and the Function Reference section of the Manual in general-- has proven to endure as a worthy endeavor. Such practice may lack excitement, but it is nonetheless a fine way to exercise the PHP skill-set, and strengthen one's sensibilities for problem-solving. :-)

Enrique M. Talavera 11 years, 11 months ago  # | flag

Very useful, i like the similarities between php,c and java.

Created by sameer borate on Thu, 11 Sep 2008 (MIT)
PHP recipes (51)
sameer borate's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks