Skip to content

Commit bcfecdc

Browse files
committed
Added code to insert at first position of a Linked List
1 parent ec1f0d2 commit bcfecdc

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

chap-03/linked-lists.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,9 @@
1818
$bookTitles->insert("Programming Intelligence");
1919

2020
// Display data
21+
$bookTitles->display();
22+
23+
// Insert a new book as the first element of the list.
24+
$bookTitles->insertAtFirst("Introducing PHP to noobs");
25+
2126
$bookTitles->display();

src/Chapter03/LinkedList.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,25 @@ public function display()
4646
}
4747
}
4848

49+
/**
50+
* Inserts a node as the first node in the linked list.
51+
* We need to take care to set the previous first node as the next value of the inserted node.
52+
* @param string|null $data
53+
* @return bool
54+
*/
55+
public function insertAtFirst(string $data = NULL)
56+
{
57+
$newNode = new ListNode($data);
58+
59+
if ($this->_firstNode === NULL) {
60+
$this->_firstNode = &$newNode;
61+
} else {
62+
$currentFirstNode = $this->_firstNode;
63+
$this->_firstNode = &$newNode;
64+
$newNode->next = $currentFirstNode;
65+
}
66+
$this->_totalNodes++;
67+
return true;
68+
}
69+
4970
}

0 commit comments

Comments
 (0)