Delete last node of linked list in php

Php program for Delete last node of linked list. Here problem description and explanation.

<?php
/*
    Php program for
    Delete the last node of singly 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 $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;
		}
		// Set new last node
		$this->tail = $node;
	}
	// Display linked list element
	public	function display()
	{
		if ($this->head == NULL)
		{
			printf("%s\n", "Empty Linked List");
			return;
		}
		$temp = $this->head;
		// iterating linked list elements
		while ($temp != NULL)
		{
			printf("%d → ", $temp->data);
			// Visit to next node
			$temp = $temp->next;
		}
		printf("%s\n", "NULL");
	}
	// Delete last node of singly linked list
	public	function deleteLastNode()
	{
		if ($this->head == NULL)
		{
			printf("%s\n", "Empty Linked List");
			return;
		}
		else
		{
			$temp = $this->head;
			$find = NULL;
			// Find second last node
			while ($temp->next != NULL)
			{
				$find = $temp;
				$temp = $temp->next;
			}
			if ($find == NULL)
			{
				// Delete head node of linked list
				$this->head = NULL;
				$this->tail = NULL;
			}
			else
			{
				// Set new last node
				$this->tail = $find;
				$find->next = NULL;
			}
		}
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Linked list
		// 1 → 2 → 3 → 4 → 5 → 6 → NULL
		$sll->addNode(1);
		$sll->addNode(2);
		$sll->addNode(3);
		$sll->addNode(4);
		$sll->addNode(5);
		$sll->addNode(6);
		printf("%s\n", "Before Delete ");
		$sll->display();
		$sll->deleteLastNode();
		printf("%s\n", "After Delete ");
		$sll->display();
	}
}

SingleLL::main(array());

Output

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







© 2022, kalkicode.com, All rights reserved