Insert linked list node at nth last position in php

Php program for Insert linked list node at nth last position.Here problem description and explanation.

<?php
// Php program for
// Insert linked list node at nth last position 

// Linked list node
class LinkNode
{
	public $data;
	public $next;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->next = NULL;
	}
}

class LinkedList
{
	public $head;
	public	function __construct()
	{
		$this->head = NULL;
	}
	// insert node at end position
	public	function insert($value)
	{
		// Create a new node
		$node = new LinkNode($value);
		if ($this->head == NULL)
		{
			$this->head = $node;
		}
		else
		{
			$temp = $this->head;
			// Find the last node
			while ($temp->next != NULL)
			{
				// Visit to next node
				$temp = $temp->next;
			}
			// Add 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("%s\n", "NULL");
	}
	// Add node at specific position from the end of linked list
	public	function endPosition($position, $value)
	{
		if ($this->head == NULL)
		{
			printf("%s\n", "Empty Linked list");
		}
		else if ($position <= 0)
		{
			printf("%s\n", "Invalid position");
		}
		else
		{
			$temp = $this->head;
			$location = NULL;
			while ($temp != NULL)
			{
				$position--;
				if ($position <= 0)
				{
					if ($location == NULL)
					{
						$location = $this->head;
					}
					else
					{
						$location = $location->next;
					}
				}
				// visit to next node
				$temp = $temp->next;
			}
			if ($position <= 1)
			{
				$node = new LinkNode($value);
				if ($location == NULL)
				{
					// Add node at first place
					$node->next = $this->head;
					$this->head = $node;
				}
				else
				{
					// Add node at intermediate position
					$node->next = $location->next;
					$location->next = $node;
				}
			}
			else
			{
				printf("%s\n", "Opps position not found");
			}
		}
	}
	public static
	function main($args)
	{
		$sll = new LinkedList();
		// Add node
		$sll->insert(5);
		$sll->insert(4);
		$sll->insert(3);
		$sll->insert(2);
		$sll->insert(1);
		$sll->display();
		$position = 2;
		$data = 10;
		$sll->endPosition($position, $data);
		printf("%s\n", " Add ".$data.
			" at last ".$position.
			"-nd position");
		$sll->display();
	}
}

LinkedList::main(array());

Output

5 → 4 → 3 → 2 → 1 → NULL
 Add 10 at last 2-nd position
5 → 4 → 3 → 2 → 10 → 1 → 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