Remove every k th node of the linked list in php

Php program for Remove every k th node of the linked list. Here problem description and explanation.

<?php
// Php Program for
// delete every k-th node of the 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 at the end of linked list
	public	function addNode($value)
	{
		// Create  node
		$node = new LinkNode($value);
		if ($this->head == NULL)
		{
			$this->head = $node;
		}
		else
		{
			$temp = $this->head;
			// Find last node
			while ($temp->next != NULL)
			{
				// Visit to next node
				$temp = $temp->next;
			}
			// Add node at last position
			$temp->next = $node;
		}
	}
	// Display all Linked List elements
	public	function display()
	{
		if ($this->head != NULL)
		{
			$temp = $this->head;
			while ($temp != NULL)
			{
				// Display node value
				printf("%d   ", $temp->data);
				// Visit to next node
				$temp = $temp->next;
			}
		}
		else
		{
			printf("%s\n", "Empty Linked list\n");
		}
	}
	public	function removeKh($kth)
	{
		if ($this->head == NULL)
		{
			// When no element
			printf("%s\n", "Empty Linked list");
		}
		else if ($kth <= 0)
		{
			printf("\nInvalid position %d ".$kth);
		}
		else
		{
			$temp = $this->head;
			$hold = NULL;
			$checker = NULL;
			$count = 0;
			if ($kth == 1)
			{
				// When delete all element
				$this->head = NULL;
			}
			while ($temp != NULL)
			{
				$count++;
				if ($count % $kth == 0)
				{
					// When delete node found
					$hold = $temp;
				}
				else
				{
					// Get current node
					$checker = $temp;
				}
				$temp = $temp->next;
				// When get free node
				if ($hold != NULL)
				{
					if ($checker != NULL)
					{
						// Unlink node
						$checker->next = $hold->next;
					}
					$hold = NULL;
				}
			}
		}
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Linked list
		// 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
		$sll->addNode(1);
		$sll->addNode(2);
		$sll->addNode(3);
		$sll->addNode(4);
		$sll->addNode(5);
		$sll->addNode(6);
		$sll->addNode(7);
		$position = 2;
		printf("%s\n", "Position : ".$position);
		printf("%s\n", "Before Delete Linked List");
		$sll->display();
		$sll->removeKh($position);
		printf("%s\n", "\n After Linked List");
		$sll->display();
	}
}

SingleLL::main(array());

Output

Position : 2
Before Delete Linked List
1   2   3   4   5   6   7
 After Linked List
1   3   5   7


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