Skip to main content

Find second last element of linked list in php

Php program for Find second last element of linked list. Here more information.

<?php
// Php program for
// Find the second last node of a 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 insert($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 strval($temp->data).
			" → ";
			// Visit to next node
			$temp = $temp->next;
		}
		echo "null\n";
	}
	//Find the second last node of a linked list
	public	function secondLast()
	{
		$node = $this->head;
		if ($node == NULL)
		{
			echo "Empty linked list\n";
		}
		else if ($node->next == NULL)
		{
			echo "Only one node in this linked list\n";
		}
		else
		{
			// Find second last node
			while ($node->next != NULL && $node->next->next != NULL)
			{
				// Visit to second next node
				$node = $node->next->next;
			}
			printf("Second last element is : %d\n",$node->data);
		}
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Add linked list node
		$sll->insert(6);
		$sll->insert(3);
		$sll->insert(2);
		$sll->insert(7);
		$sll->insert(1);
		$sll->insert(9);
		echo "Linked List\n";
		// 6 → 3 → 2 → 7 → 1 → 9 → null
		$sll->display();
		$sll->secondLast();
	}
}
SingleLL::main(array());

Output

Linked List
6 → 3 → 2 → 7 → 1 → 9 → null
Second last element is : 1




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