Skip to main content

Reversal order of linked list using recursion in php

Php program for Reversal order of linked list using recursion . Here more information.

<?php
// Php program for
// Print reverse of a linked list without actually reversing

// Linked list node
class LinkNode
{
	public $data;
	public $next;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->next = NULL;
	}
}
class SingleLL
{
	public $head;
	public $tail;
	public	function __construct()
	{
		$this->head = NULL;
		$this->tail = NULL;
	}
	// Add new Node at end of linked list 
	public	function addNode($data)
	{
		$node = new LinkNode($data);
		if ($this->head == NULL)
		{
			$this->head = $node;
		}
		else
		{
			// Append the node at last position
			$this->tail->next = $node;
		}
		$this->tail = $node;
	}
	// Display reversal view of linked list using recursion
	public	function printReverse($node)
	{
		if ($node == NULL)
		{
			return;
		}
		// Visit to next node
		$this->printReverse($node->next);
		// Display node value
		echo "  ",$node->data;
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		//  1 → 2 → 8 → 4 → 9 → 6 → NULL
		$sll->addNode(1);
		$sll->addNode(2);
		$sll->addNode(8);
		$sll->addNode(4);
		$sll->addNode(9);
		$sll->addNode(6);
		// Reversal view
		// 6 9 4 8 2 1
		$sll->printReverse($sll->head);
	}
}
SingleLL::main(array());

Output

  6  9  4  8  2  1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment