Reversing a list

There are many approaches to reversing a linked list. We will work on a simple approach to reverse the list, which is known as in place reverse. We iterate through the nodes and change the next node to the previous, previous to the current, and the current to the next. A pseudo algorithm for the logic will look like this:

prev   = NULL; 
current = first_node;
next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
first_node = prev;

If we implement our reverse function based on this pseudocode, it will look like this:

    public function reverse() { 
if ($this->_firstNode !== NULL) {
if ($this->_firstNode->next !== NULL) {
$reversedList = NULL;
$next = NULL;
$currentNode = $this->_firstNode;
while ($currentNode !== NULL) {
$next = $currentNode->next;
$currentNode->next = $reversedList;
$reversedList = $currentNode;
$currentNode = $next;
}
$this->_firstNode = $reversedList;
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset