Delete middle node from linked list in php

Php program for Delete middle node from linked list. Here problem description and explanation.

<?php
/*
    Php program for
    Delete middle node 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;
	}
	// Adding new node at beginning of linked list
	public	function addNode($data)
	{
		// Create new node
		$node = new LinkNode($data);
		// Connect current node to previous head
		$node->next = $this->head;
		$this->head = $node;
	}
	// Display linked list element
	public	function display()
	{
		if ($this->head == NULL)
		{
			return;
		}
		$temp = $this->head;
		// iterating linked list elements
		while ($temp != NULL)
		{
			// Display node value
			printf("%s", strval($temp->data).
				" → ");
			// Visit to next node
			$temp = $temp->next;
		}
		printf("%s", " NULL\n");
	}
	// Delete the middle node of linked list
	public	function deleteMid()
	{
		if ($this->head == NULL)
		{
			// When linked list are no elements
			printf("%s\n", "Empty Linked List");
		}
		else if ($this->head->next == NULL && 
                 $this->head->next->next == NULL)
		{
			// When linked list are less than  of 3 nodes
			printf("%s\n", "Less then 3 node of linked list");
		}
		else
		{
			$temp = $this->head;
			$midPrevious = NULL;
			// Find the middle and its previous node
			while ($temp != NULL && $temp->next != NULL && 
                   $temp->next->next != NULL)
			{
				if ($midPrevious == NULL)
				{
					// When first node
					$midPrevious = $temp;
				}
				else
				{
					// Visit to next node
					$midPrevious = $midPrevious->next;
				}
				// Visit to next second next node
				$temp = $temp->next->next;
			}
			// Get the node which is deleting 
			$temp = $midPrevious->next;
			// Show deleted node
			printf("%s\n", "Delete node : ".strval($temp->data));
			// Change link
			$midPrevious->next = $temp->next;
		}
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Linked list
		// 7 → 6 → 5 → 4 → 3 → 2 → 1 → NULL
		$sll->addNode(1);
		$sll->addNode(2);
		$sll->addNode(3);
		$sll->addNode(4);
		$sll->addNode(5);
		$sll->addNode(6);
		$sll->addNode(7);
		printf("%s\n", "Before Delete middle node");
		$sll->display();
		// Delete middle node
		$sll->deleteMid();
		printf("%s\n", "After Delete middle node");
		$sll->display();
	}
}
SingleLL::main(array());

Output

Before Delete middle node
7 → 6 → 5 → 4 → 3 → 2 → 1 →  NULL
Delete node : 4
After Delete middle node
7 → 6 → 5 → 3 → 2 → 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