Sorted order insertion of linked list in php

Php program for Sorted order insertion of linked list. Here problem description and explanation.

<?php
/*
    Php program for
    Add node in sorted order of linked list
*/
// Linked list node
class LinkNode
{
	public $data;
	public $next;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->next = NULL;
	}
}

class SingleLL
{
	public $head;
	public	function __construct()
	{
		$this->head = NULL;
	}
	// Add new node in sorted order
	public	function sortedAdd($data)
	{
		// Create new node
		$node = new LinkNode($data);
		if ($this->head == NULL || 
            $this->head->data >= $data)
		{
			// When linked list empty
			// or new nodes are adding at beginning
			$node->next = $this->head;
			$this->head = $node;
		}
		else
		{
			$temp = $this->head;
			// Find position to add new node
			while ($temp->next != NULL && 
                   $temp->next->data < $data)
			{
				// Visit to next node
				$temp = $temp->next;
			}
			$node->next = $temp->next;
			// Add new node
			$temp->next = $node;
		}
	}
	// Display linked list element
	public	function display()
	{
		if ($this->head == NULL)
		{
			return;
		}
		$temp = $this->head;
		// Iterating linked list elements
		while ($temp != NULL)
		{
			printf("%s → ",$temp->data);
			// Visit to next node
			$temp = $temp->next;
		}
		printf("NULL\n");
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Add Linked list node
		$sll->sortedAdd(1);
		$sll->sortedAdd(-3);
		$sll->sortedAdd(9);
		$sll->sortedAdd(4);
		$sll->sortedAdd(11);
		$sll->sortedAdd(-7);
		printf("Linked List \n");
		// -7 → -3 → 1 → 4 → 9 → 11 → NULL
		$sll->display();
	}
}

SingleLL::main(array());

Output

Linked List
-7 → -3 → 1 → 4 → 9 → 11 → NULL


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







© 2021, kalkicode.com, All rights reserved