Posted on by Kalkicode
Code Single linked list

Sum of unique elements in linked list in java

Java program for Sum of unique elements in linked list . Here problem description and explanation.

// Java Program for
// Sum of unique elements in linked list 

// Linked list node
class LinkNode
{
	public int data;
	public LinkNode next;
	public LinkNode(int data)
	{
		this.data = data;
		this.next = null;
	}
}
public class SingleLL
{
	public LinkNode head;
	public LinkNode tail;
	public SingleLL()
	{
		// Set head and tail 
		this.head = null;
		this.tail = null;
	}
	// Add new node at the end of linked list
	public void insert(int value)
	{
		// Create a new node
		LinkNode node = new LinkNode(value);
		if (this.head == null)
		{
			this.head = node;
		}
		else
		{
			this.tail.next = node;
		}
		this.tail = node;
	}
	// Display linked list element
	public void display()
	{
		if (this.head == null)
		{
			return;
		}
		LinkNode temp = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			System.out.print(temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		System.out.println("NULL");
	}
	// return the sum of distinct element
	public int distinctSum()
	{
		int result = 0;
		boolean flag;
		LinkNode 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 void main(String[] args)
	{
		SingleLL 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);
		System.out.println("Linked List");
		sll.display();
		System.out.println("Distinct Node sum : " + sll.distinctSum());
	}
}

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