Subtraction of alternate nodes of linked list in c#
Csharp program for Subtraction of alternate nodes of linked list. Here more information.
// Include namespace system
using System;
/*
Csharp program for
Subtraction of the alternate nodes of linked list
*/
// Linked list node
public 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 initial value
this.head = null;
this.tail = null;
}
public void insert(int data)
{
var node = new LinkNode(data);
if (this.head == null)
{
// Add first node
this.head = node;
}
else
{
// Add node at the end position
this.tail.next = node;
}
// New last node
this.tail = node;
}
// Display linked list element
public void display()
{
if (this.head == null)
{
return;
}
var temp = this.head;
// iterating linked list elements
while (temp != null)
{
Console.Write(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
Console.WriteLine(" NULL");
}
// Find the subtraction of all alternate
// nodes in linked list
public void alternateSubtraction()
{
// Define resultant variables
var result = 0;
var counter = 0;
// Start to first node of linked list
var temp = this.head;
// iterating linked list elements
while (temp != null)
{
if (counter % 2 == 0)
{
// When get alternate node
if (result == 0)
{
result = temp.data;
}
else
{
result = result - temp.data;
}
}
// Node counter
counter++;
// Visit to next node
temp = temp.next;
}
Console.WriteLine(" Alternate nodes subtraction : " +
result);
}
public static void Main(String[] args)
{
var sll = new SingleLL();
// Add node in linked list
// 4 → 7 → 2 → 9 → 1 → 3 → 4 → 3 → 6 → NULL
sll.insert(4);
sll.insert(7);
sll.insert(2);
sll.insert(9);
sll.insert(1);
sll.insert(3);
sll.insert(4);
sll.insert(3);
sll.insert(6);
// Display of linked list nodes
sll.display();
// Test
sll.alternateSubtraction();
}
}
Output
4 → 7 → 2 → 9 → 1 → 3 → 4 → 3 → 6 → NULL
Alternate nodes subtraction : -9
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