# 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
*/
{
var data: Int;
init(_ data: Int)
{
// Set node value
self.data = data;
self.next = nil;
}
}
class SingleLL
{
init()
{
self.tail = nil;
}
// Insert node at last of linked list
func insert(_ value: Int)
{
// Create a node
{
}
else
{
self.tail!.next = node;
}
self.tail = node;
}
func display()
{
{
print(" Linked List :", terminator: "");
while (temp  != nil)
{
// Display node data
print("",temp!.data, terminator: " ");
// Visit to next node
temp = temp!.next;
}
}
else
{
}
}
func findBalancedNode()
{
// Define Useful resultant variables
// 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
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();
sll1.insert(1);
sll1.insert(2);
sll1.insert(3);
sll1.insert(4);
sll1.insert(2);
sll1.insert(1);
sll1.insert(3);
sll2.insert(1);
sll2.insert(3);
sll2.insert(6);
sll2.insert(1);
sll2.insert(1);
sll2.insert(1);
sll2.insert(1);
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``````

## 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.