Skip to main content

Subtraction of alternate nodes of linked list in swift

Swift program for Subtraction of alternate nodes of linked list. Here problem description and other solutions.

import Foundation
/*
    Swift 4 program for
    Subtraction of the alternate nodes of linked list
*/
// Linked list node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
	}
}
class SingleLL
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	func insert(_ data: Int)
	{
		let node: LinkNode? = LinkNode(data);
		if (self.head == nil)
		{
			// Add first node
			self.head = node;
		}
		else
		{
			// Add node at the end position
			self.tail!.next = node;
		}
		// New last node
		self.tail = node;
	}
	// Display linked list element
	func display()
	{
		if (self.head == nil)
		{
			return;
		}
		var temp: LinkNode? = self.head;
		// iterating linked list elements
		while (temp  != nil)
		{
			print(" ",temp!.data, terminator: " →");
			// Visit to next node
			temp = temp!.next;
		}
		print(" NULL");
	}
	// Find the subtraction of all alternate 
	// nodes in linked list
	func alternateSubtraction()
	{
		// Define resultant variables
		var result: Int = 0;
		var counter: Int = 0;
		// Start to first node of linked list
		var temp: LinkNode? = self.head;
		// iterating linked list elements
		while (temp  != nil)
		{
			if (counter % 2 == 0)
			{
				// When get alternate node
				if (result == 0)
				{
					result = temp!.data;
				}
				else
				{
					result = result - temp!.data;
				}
			}
			// Node counter
			counter += 1;
			// Visit to next node
			temp = temp!.next;
		}
		print(" Alternate nodes subtraction :",result);
	}
	static func main()
	{
		let sll: SingleLL = 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();

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