Find the balanced node of linked list in swift
Swift program for Find the balanced node of linked list. Here problem description and explanation.
import Foundation
/*
Swift 4 program for
Find the balanced node in a linked list
*/
// Node of LinkedList
class LinkNode
{
var data: Int;
var next: LinkNode? ;
init(_ data: Int)
{
// Set node value
self.data = data;
self.next = nil;
}
}
class SingleLL
{
var head: LinkNode? ;
var tail: LinkNode? ;
init()
{
self.head = nil;
self.tail = nil;
}
// Insert node at last of linked list
func insert(_ value: Int)
{
// Create a node
let node: LinkNode? = LinkNode(value);
if (self.head == nil)
{
// When linked list empty
// Add first node
self.head = node;
}
else
{
// Add new node at end of linked list
self.tail!.next = node;
}
self.tail = node;
}
// Display linked list nodes
func display()
{
if (self.head != nil)
{
print(" Linked List :", terminator: "");
var temp: LinkNode? = self.head;
while (temp != nil)
{
// Display node data
print("",temp!.data, terminator: " ");
// Visit to next node
temp = temp!.next;
}
}
else
{
print("Empty Linked List");
}
}
func findBalancedNode()
{
// Define Useful resultant variables
var temp: LinkNode? = self.head;
var result: LinkNode? = nil;
// Define Useful calculations variables
var totalSum: Int = 0;
var currentSum: Int = 0;
// Sum of all nodes
while (temp != nil)
{
// sum of node value
totalSum += temp!.data;
// Visit to next node
temp = temp!.next;
}
// Get first node of linked list
temp = self.head;
while (temp != nil && result == nil)
{
if (totalSum - (currentSum + temp!.data) == currentSum)
{
// When current node is balanced node
result = temp;
}
// Calculate node sum
currentSum += temp!.data;
// Visit to next node
temp = temp!.next;
}
if (result != nil)
{
print("\n Balanced node is : ",result!.data);
}
else
{
print("\n Balanced node not exist");
}
}
static func main()
{
let sll1: SingleLL = SingleLL();
let sll2: SingleLL = SingleLL();
let sll3: SingleLL = SingleLL();
// Create first linked list
sll1.insert(1);
sll1.insert(2);
sll1.insert(3);
sll1.insert(4);
sll1.insert(2);
sll1.insert(1);
sll1.insert(3);
// Second linked list
sll2.insert(1);
sll2.insert(3);
sll2.insert(6);
sll2.insert(1);
sll2.insert(1);
sll2.insert(1);
sll2.insert(1);
// Third linked list
sll3.insert(1);
sll3.insert(2);
sll3.insert(3);
// Display node elements
sll1.display();
// Find balanced node
sll1.findBalancedNode();
// Display node elements
sll2.display();
// Find balanced node
sll2.findBalancedNode();
// Display node elements
sll3.display();
// Find balanced node
sll3.findBalancedNode();
}
}
SingleLL.main();
Output
Linked List : 1 2 3 4 2 1 3
Balanced node is : 4
Linked List : 1 3 6 1 1 1 1
Balanced node is : 6
Linked List : 1 2 3
Balanced node not exist
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