Remove duplicates from unsorted linked list in php

Php program for Remove duplicates from unsorted linked list. Here problem description and explanation.

<?php
// Php Program to 
// Delete duplicate nodes in unsorted linked list
class LinkNode
{
	public $data;
	public $next;
	public	function __construct($data)
	{
		$this->data = $data;
		$this->next = NULL;
	}
}
class LinkedList
{
	public $head;
	public $tail;
	// Class constructors
	public	function __construct()
	{
		$this->head = NULL;
		$this->tail = NULL;
	}
	// Insert new element at end position
	public	function insert($value)
	{
		// Create new node
		$node = new LinkNode($value);
		if ($this->head == NULL)
		{
			// Add first node
			$this->head = $node;
		}
		else
		{
			// Add new node at the last position
			$this->tail->next = $node;
		}
		// Make new tail 
		$this->tail = $node;
	}
	// Display all node value
	public	function display()
	{
		if ($this->head != NULL)
		{
			printf("%s", "Linked List Element :");
			$temp = $this->head;
			while ($temp != NULL)
			{
				// Display node value
				printf("%d  ",$temp->data);
				// Visit to next node
				$temp = $temp->next;
			}
		}
		else
		{
			printf("Empty Linked list\n");
		}
	}
	public	function removeNode()
	{
		if ($this->head == NULL)
		{
			// When linked list empty
			printf("Empty Linked list");
		}
		else
		{
			// Auxiliary variable
			$temp = $this->head;
			$hold = NULL;
			$initial = NULL;
			$current = NULL;
			// Outer loop
			while ($temp != NULL)
			{
				// New last node
				$this->tail = $temp;
				$current = $temp;
				$initial = $current->next;
				// Inner loop
				// Remove all node which value is similar to temp node
				while ($initial != NULL)
				{
					if ($temp->data == $initial->data)
					{
						// Get remove node
						$hold = $initial;
					}
					else
					{
						$current = $initial;
					}
					// Visit to next node
					$initial = $initial->next;
					if ($hold != NULL)
					{
						$current->next = $initial;
						// remove node
						$hold = NULL;
					}
				}
				// Visit to next node
				$temp = $temp->next;
			}
		}
	}
	public static
	function main($args)
	{
		// new linked list
		$task = new LinkedList();
		// Add tested element
		$task->insert(1);
		$task->insert(2);
		$task->insert(9);
		$task->insert(4);
		$task->insert(9);
		$task->insert(3);
		$task->insert(1);
		$task->insert(7);
		$task->insert(2);
		$task->insert(1);
		printf("\nBefore Delete\n");
		$task->display();
		$task->removeNode();
		printf("\nAfter Delete\n");
		$task->display();
	}
}

LinkedList::main(array());

Output

Before Delete
Linked List Element :1  2  9  4  9  3  1  7  2  1
After Delete
Linked List Element :1  2  9  4  3  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