Completed
Push — master ( f6a034...2cb83b )
by Siro Díaz
01:26
created

DoublyLinkedList::lastIndexOf()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
dl 19
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 1
1
<?php
2
/**
3
 * DataStructures for PHP
4
 *
5
 * @link      https://github.com/SiroDiaz/DataStructures
6
 * @copyright Copyright (c) 2017 Siro Díaz Palazón
7
 * @license   https://github.com/SiroDiaz/DataStructures/blob/master/README.md (MIT License)
8
 */
9
namespace DataStructures\Lists;
10
11
use DataStructures\Lists\Traits\{CountTrait, ArrayAccessTrait};
12
use DataStructures\Lists\Nodes\DoublyLinkedListNode as Node;
13
use DataStructures\Lists\Interfaces\ListInterface;
14
use OutOfBoundsException;
15
16
/**
17
 * DoublyLinkedList
18
 *
19
 * DoublyLinkedList is a double linked list that has
20
 * a pointer to the next and the previous node.
21
 *
22
 * @author Siro Diaz Palazon <[email protected]>
23
 */
24
class DoublyLinkedList implements ListInterface {
25
    use ArrayAccessTrait;
26
27
    private $head;
28
    private $tail;
29
    private $size;
30
    private $position;
31
    private $current;
32
33 View Code Duplication
    public function __construct() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
34
        $this->head = null;
35
        $this->tail = &$this->head;
36
        $this->size = 0;
37
        $this->position = 0;
38
        $this->current = &$this->head;
39
    }
40
41
    /**
42
     * Removes all nodes of the list. It removes from the beginning.
43
     */
44
    public function clear() {
45
        while($this->head !== null) {
46
            $this->shift();
47
        }
48
    }
49
    
50
    /**
51
     * Gets the data stored in the position especified.
52
     *
53
     * @param integer $index Index that must be greater than 0
54
     *  and lower than the list size.
55
     * @return mixed The data stored in the given index
56
     * @throws OutOfBoundsException if index is out bounds.
57
     */
58 View Code Duplication
    public function get($index) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
59
        $node = $this->search($index);
60
        if($node === null) {
61
            return null;
62
        }
63
64
        return $node->data;
65
    }
66
67
    /**
68
     * Gets the node stored in the position especified.
69
     * If index is 0 or (size - 1) the method is O(1) else O(n).
70
     *
71
     * @param integer $index the position.
72
     * @throws OutOfBoundsException if it is out of limits (< 0 or > size - 1)
73
     * @return DataStructures\Lists\Nodes\DoublyLinkedListNode|null the node stored in $index.
74
     */
75
    protected function search($index) {
76
        if($index < 0 || $index > $this->size - 1) {
77
            throw new OutOfBoundsException();
78
        }
79
80
        if($index === 0) {
81
            return $this->head;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->head; of type null|DataStructures\List...es\DoublyLinkedListNode adds the type DataStructures\Lists\Nodes\DoublyLinkedListNode to the return on line 81 which is incompatible with the return type documented by DataStructures\Lists\DoublyLinkedList::search of type DataStructures\Lists\Dat...ublyLinkedListNode|null.
Loading history...
82
        }
83
84
        if($index === $this->size - 1) {
85
            return $this->tail;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->tail; of type null|DataStructures\List...es\DoublyLinkedListNode adds the type DataStructures\Lists\Nodes\DoublyLinkedListNode to the return on line 85 which is incompatible with the return type documented by DataStructures\Lists\DoublyLinkedList::search of type DataStructures\Lists\Dat...ublyLinkedListNode|null.
Loading history...
86
        }
87
88
        $current = &$this->head;
89
        if($index < (int) ceil($this->size / 2)) {
90
            $i = 0;
91
            while($i < $index) {
92
                $current = &$current->next;
93
                $i++;
94
            }    
95
        } else {
96
            $i = $this->size;
97
            while($i > $index) {
98
                $current = &$current->prev;
99
                $i--;
100
            }
101
        }
102
103
        return $current;
104
    }
105
106
    /**
107
     * Returns the data in the last node with O(1).
108
     *
109
     * @return mixed null if the list is empty.
110
     */
111
    public function getLast() {
112
        if($this->head === null) {
113
            return null;
114
        }
115
        return $this->tail->data;
116
    }
117
118
    /**
119
     * Returns the last node with O(1).
120
     *
121
     * @return DataStructures\Lists\Nodes\DoublyLinkedListNode|null if the list is empty.
122
     */
123
    public function searchLast() {
124
        if($this->head === null) {
125
            return null;
126
        }
127
        return $this->tail;
128
    }
129
130
    /**
131
     *
132
     */
133
    public function contains($data) : bool {
134
        if($this->empty()) {
135
            return false;
136
        }
137
138
        $current = $this->head->next;
139
        $prev = $this->head;
140
        while($current !== $this->head) {
141
            if($prev->data === $data) {
142
                return true;
143
            }
144
            $prev = $current;
145
            $current = $current->next;
146
        }
147
148
        return false;
149
    }
150
151
    /**
152
     *
153
     */
154 View Code Duplication
    public function indexOf($data) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
155
        if($this->head === null) {
156
            return false;
157
        }
158
        
159
        $current = $this->head;
160
        $i = 0;
161
        
162
        while($i < $this->size) {
163
            if($current->data == $data) {
164
                return $i;
165
            }
166
167
            $current = $current->next;
168
            $i++;
169
        }
170
171
        return false;
172
    }
173
174
    /**
175
     *
176
     */
177 View Code Duplication
    public function lastIndexOf($data) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
178
        if($this->head === null) {
179
            return false;
180
        }
181
        
182
        $current = $this->head;
183
        $i = 0;
184
        $pos = false;
185
        while($i < $this->size) {
186
            if($current->data == $data) {
187
                $pos = $i;
188
            }
189
190
            $current = $current->next;
191
            $i++;
192
        }
193
194
        return $pos;
195
    }
196
    
197
    /**
198
     * Generator for retrieve all nodes stored.
199
     * 
200
     * @return null if the head is null (or list is empty)
201
     */
202 View Code Duplication
    public function getAll() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
        if($this->head === null) {
204
            return;
205
        }
206
207
        if($this->head === $this->tail) {
208
            yield $this->head->data;
209
        } else {
210
            $current = $this->head;
211
            $i = 0;
212
            while($i < $this->size) {
213
                yield $current->data;
214
                $current = $current->next;
215
                $i++;
216
            }
217
        }
218
    }
219
220
    /**
221
     * Inserts data in the specified position.
222
     *
223
     * @param integer $index the position.
224
     * @param mixed $data the data to store.
225
     */
226 View Code Duplication
    public function insert($index, $data) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
227
        if($index < 0) {
228
            throw new OutOfBoundsException();
229
        }
230
231
        if($index === 0) {
232
            $this->insertBeginning($data);
233
        } else if($index >= $this->size) {
234
            $this->insertEnd($data);
235
        } else if($index > 0 && $index < $this->size) {
236
            $this->insertAt($index, $data);
237
        }
238
        
239
        $this->size++;
240
    }
241
242
    /**
243
     * Inserts at the beginning of the list.
244
     *
245
     * @param mixed $data
246
     */
247
    private function insertBeginning($data) {
248
        $newNode = new Node($data);
249
        if($this->head === null) {
250
            $newNode->next = &$this->head;
251
            $newNode->prev = &$this->head;
252
            $this->head = &$newNode;
253
            $this->tail = &$newNode;
254
        } else {
255
            $this->tail->next = &$newNode;
256
            $newNode->next = &$this->head;
257
            $newNode->prev = &$this->tail;
258
            $this->head = &$newNode;
259
        }
260
    }
261
262
    /**
263
     * Add a new node in the specified index.
264
     *
265
     * @param mixed $data the data to be stored.
266
     */
267
    private function insertEnd($data) {
268
        $newNode = new Node($data);
269
        $this->tail->next = &$newNode;
270
        $newNode->next = &$this->head;
271
        $newNode->prev = &$this->tail;
272
        $this->tail = &$newNode;
273
        $this->head->prev = &$newNode;
274
    }
275
276
    /**
277
     * Add a new node in the specified index.
278
     *
279
     * @param integer $index the position.
280
     * @param mixed $data the data to be stored.
281
     */
282
    private function insertAt($index, $data) {
283
        $newNode = new Node($data);
284
        $current = $this->head;
285
        $prev = null;
286
        $i = 0;
287
        while($i < $index) {
288
            $prev = $current;
289
            $current = $current->next;
290
            $i++;
291
        }
292
        
293
        $prev->next = &$newNode;
294
        $newNode->prev = &$prev;
295
        $newNode->next = &$current;
296
        $current->prev = &$newNode;
297
    }
298
299
    /**
300
     * Adds at the end of the list new node containing
301
     * the data to be stored.
302
     *
303
     * @param mixed $data The data
304
     */
305
    public function push($data) {
306
        $this->insert($this->size, $data);
307
    }
308
309
    /**
310
     * Adds at the beginning a node in the list.
311
     *
312
     * @param mixed $data
313
     * @return mixed the data stored.
314
     */
315
    public function unshift($data) {
316
        $this->insert(0, $data);
317
    }
318
    
319
    /**
320
     * Delete a node in the given position and returns it back.
321
     *
322
     * @param integer $index the position.
323
     * @throws OutOfBoundsException if index is negative
324
     *  or is greater than the size of the list.
325
     */
326 View Code Duplication
    public function delete($index) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
327
        if($index < 0 || ($index > 0 && $index > $this->size - 1)) {
328
            throw new OutOfBoundsException();
329
        }
330
331
        // if the list is empty
332
        if($this->head === null) {
333
            return null;
334
        }
335
        
336
        // if only there is an element
337
        if($this->head->next === $this->head) {
338
            $temp = $this->head;
339
            $this->head = null;
340
            $this->size--;
341
342
            return $temp->data;
343
        }
344
345
        if($index === 0) {
346
            return $this->deleteBeginning();
347
        } else if($index === $this->size - 1) {
348
            return $this->deleteEnd();
349
        } else {
350
            return $this->deleteAt($index);
351
        }
352
    }
353
354
    /**
355
     * Deletes at the beginnig of the list and returns the data stored.
356
     *
357
     * @return mixed the data stored in the node.
358
     */
359 View Code Duplication
    private function deleteBeginning() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
360
        $temp = $this->head;
361
        $this->head = &$this->head->next;
362
        $this->tail->next = &$this->head;
363
        $this->size--;
364
365
        return $temp->data;
366
    }
367
368
    /**
369
     * Deletes at the specified position and returns the data stored.
370
     *
371
     * @param integer $index the position.
372
     * @return mixed the data stored in the node.
373
     */
374
    private function deleteAt($index) {
375
        $i = 0;
376
        $prev = $this->head;
377
        $current = $this->head;
378
        
379
        while($i < $index) {
380
            $prev = $current;
381
            $current = $current->next;
382
            $i++;
383
        }
384
385
        $temp = $current;
386
        $prev->next = &$current->next;
387
        $current->next->prev = &$pre;
0 ignored issues
show
Bug introduced by
The variable $pre does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
388
        $current = null;
0 ignored issues
show
Unused Code introduced by
$current is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
389
        $this->size--;
390
391
        return $temp->data;
392
    }
393
394
    /**
395
     * Deletes at the end of the list and returns the data stored.
396
     *
397
     * @return mixed the data stored in the node.
398
     */
399 View Code Duplication
    private function deleteEnd() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
400
        $prev = $this->head;
401
        $current = $this->head;
402
        
403
        while($current !== $this->tail) {
404
            $prev = $current;
405
            $current = $current->next;
406
        }
407
        
408
        $temp = $current;
409
        $prev->next = &$this->head;
410
        $this->head->prev = &$prev;
411
        $this->tail = &$prev;
412
        $current = null;
0 ignored issues
show
Unused Code introduced by
$current is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
413
414
        $this->size--;
415
416
        return $temp->data;
417
    }
418
419
    /**
420
     * Deletes the first node of the list and returns it.
421
     *
422
     * @return mixed the data.
423
     */
424
    public function shift() {
425
        return $this->delete(0);
426
    }
427
428
    /**
429
     * Removes and returns the last node in the list.
430
     *
431
     * @return mixed data in node.
432
     */
433
    public function pop() {
434
        return $this->delete($this->size - 1);
435
    }
436
    
437
    /**
438
     * Converts/exports the list content into array type.
439
     *
440
     * @return array data stored in all nodes.
441
     */
442
    public function toArray() : array {
443
        $arr = [];
444
        foreach($this->getAll() as $node) {
445
            $arr[] = $node;
446
        }
447
448
        return $arr;
449
    }
450
451
    /**
452
     * Reset the cursor position.
453
     */
454
    public function rewind() {
455
        $this->position = 0;
456
        $this->current = &$this->head;
457
    }
458
459
    /**
460
     * Returns the current node data.
461
     *
462
     * @return mixed
463
     */
464
    public function current() {
465
        return $this->current->data;
466
    }
467
468
    /**
469
     * Key or index that indicates the cursor position.
470
     *
471
     * @return integer The current position.
472
     */
473
    public function key() {
474
        return $this->position;
475
    }
476
477
    /**
478
     * Move the cursor to the next node and increments the
479
     * position counter.
480
     */
481
    public function next() {
482
        ++$this->position;
483
        $this->current = $this->current->next;
484
    }
485
486
    /**
487
     * Returns if the current pointer position is valid.
488
     *
489
     * @return boolean true if pointer is not last, else false.
490
     */
491
    public function valid() {
492
        return $this->position < $this->size;
493
    }
494
495
    /**
496
     * Binds to count() method. This is equal to make $this->tree->size().
497
     *
498
     * @return integer the tree size. 0 if it is empty.
499
     */
500
    public function count() {
501
        return $this->size;
502
    }
503
504
    /**
505
     * Returns the array size.
506
     *
507
     * @return int the length
508
     */
509
    public function size() : int {
510
        return $this->size;
511
    }
512
513
    /**
514
     * Checks if the list is empty.
515
     *
516
     * @return boolean true if is empty, else false.
517
     */
518
    public function empty() : bool {
519
        return $this->size === 0;
520
    }
521
}