Skip to main content

Subtraction of alternate nodes of linked list in typescript

Ts program for Subtraction of alternate nodes of linked list. Here problem description and explanation.

/*
    TypeScript program for
    Subtraction of the alternate nodes of linked list
*/
// Linked list node
class LinkNode
{
	public data: number;
	public next: LinkNode;
	constructor(data: number)
	{
		this.data = data;
		this.next = null;
	}
}
class SingleLL
{
	public head: LinkNode;
	public tail: LinkNode;
	constructor()
	{
		// Set initial value
		this.head = null;
		this.tail = null;
	}
	public insert(data: number)
	{
		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 display()
	{
		if (this.head == null)
		{
			return;
		}
		var temp = this.head;
      	var result = "";
		// iterating linked list elements
		while (temp != null)
		{
			result += (" " + temp.data + " →");
			// Visit to next node
			temp = temp.next;
		}
		console.log(result, " NULL");
	}
	// Find the subtraction of all alternate 
	// nodes in linked list
	public 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.log(" Alternate nodes subtraction : " + result);
	}
	public static main()
	{
		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();
	}
}
SingleLL.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

 4 → 7 → 2 → 9 → 1 → 3 → 4 → 3 → 6 →  NULL
 Alternate nodes subtraction : -9




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