Posted on by Kalkicode
Code Single linked list

Sum of unique elements in linked list in php

Php program for Sum of unique elements in linked list . Here more information.

<?php
// Php Program for
// Sum of unique elements in 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 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)
		{
			printf("%s", strval($temp->data).
				" → ");
			// Visit to next node
			$temp = $temp->next;
		}
		printf("%s\n", "NULL");
	}
	// return the sum of distinct element
	public	function distinctSum()
	{
		$result = 0;
		$flag;
		$temp = $this->head;
		$checker = NULL;
		while ($temp != NULL)
		{
			// Reset the checker 
			$checker = $this->head;
			// Flag are used to check exist element is repeated or not
			$flag = true;
			while ($checker != NULL)
			{
				if ($checker != $temp && $checker->data == $temp->data)
				{
					// When repeated element are found
					$flag = false;
					break;
				}
				$checker = $checker->next;
			}
			if ($flag == true)
			{
				// When unique element
				$result += $temp->data;
			}
			// Visit to next node
			$temp = $temp->next;
		}
		return $result;
	}
	public static
	function main($args)
	{
		$sll = new SingleLL();
		// Linked list
		// 4 → 5 → 2 → 3 → 5 → 7 → NULL
		$sll->insert(4);
		$sll->insert(5);
		$sll->insert(2);
		$sll->insert(3);
		$sll->insert(5);
		$sll->insert(7);
		printf("Linked List\n");
		$sll->display();
		printf("Distinct Node sum : %d\n",$sll->distinctSum());
	}
}

SingleLL::main(array());

Output

Linked List
4 → 5 → 2 → 3 → 5 → 7 → NULL
Distinct Node sum : 16

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