Skip to main content

delete odd numbers from linked list in php

Php program for delete odd numbers from linked list. Here problem description and other solutions.

<?php
// Php program for
// Delete odd nodes from linked list

// Node of Linked List
class LinkNode
{
	public $data;
	public $next;
	public	function __construct($data)
	{
		//Set node value
		$this->data = $data;
		$this->next = NULL;
	}
}
class SingleLL
{
	public $head;
	public $tail;
	public	function __construct()
	{
		$this->head = NULL;
		$this->tail = NULL;
	}
	// Add new node at the end of linked list
	public	function addNode($value)
	{
		// Create a new node
		$node = new LinkNode($value);
		if ($this->head == NULL)
		{
			$this->head = $node;
		}
		else
		{
			$this->tail->next = $node;
		}
		$this->tail = $node;
	}
	// Display linked list element
	public	function display()
	{
		if ($this->head == NULL)
		{
			return;
		}
		$temp = $this->head;
		// iterating linked list elements
		while ($temp != NULL)
		{
			echo $temp->data," → ";
			// Visit to next node
			$temp = $temp->next;
		}
		echo "null\n";
	}
	// Delete all odd key nodes in linked list
	public	function deleteOddNodes()
	{
		// Define some auxiliary variables
		$current = $this->head;
		$auxiliary = NULL;
		$back = NULL;
		// iterating linked list elements
		while ($current != NULL)
		{
			if ($current->data % 2 != 0)
			{
				// When get odd node
				$auxiliary = $current;
			}
			else
			{
				$back = $current;
			}
			// Visit to next node
			$current = $current->next;
			if ($auxiliary != NULL)
			{
				// When Deleted node exists
				if ($back == NULL)
				{
					// When front node is odd node
					// head visit to next node
					$this->head = $current;
				}
				else
				{
					// When deleting centralized node
					$back->next = $current;
				}
				if ($this->tail == $auxiliary)
				{
					// When delete last node
					// Set new tail
					$this->tail = $back;
				}
				// Unlink deleted node 
				$auxiliary->next = NULL;
				$auxiliary = NULL;
			}
		}
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Add linked list node
		$sll->addNode(3);
		$sll->addNode(1);
		$sll->addNode(4);
		$sll->addNode(7);
		$sll->addNode(9);
		$sll->addNode(6);
		$sll->addNode(5);
		$sll->addNode(11);
		// Before effect
		echo "Before Delete Odd Key Nodes\n";
		// 3 → 1 → 4 → 7 → 9 → 6 → 5 → 11 → NULL
		$sll->display();
		// Perform delete operation
		$sll->deleteOddNodes();
		// After effect
		echo "After Delete Odd Key Nodes\n";
		// 4 → 6 → NULL
		$sll->display();
	}
}
SingleLL::main(array());

Output

Before Delete Odd Key Nodes
3 → 1 → 4 → 7 → 9 → 6 → 5 → 11 → null
After Delete Odd Key Nodes
4 → 6 → null




Comment

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