Skip to main content

Find length of circular linked list in swift

Swift program for Find length of circular linked list . Here problem description and explanation.

import Foundation
// Swift 4 program for
// Count number of nodes in circular linked list 

// Define class of linked list Node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int, _ first: LinkNode? )
	{
		self.data = data;
		self.next = first;
	}
}
class CircularLinkedList
{
	var head: LinkNode? ;
	// Class constructor
	init()
	{
		self.head = nil;
	}
	// Insert node at end of circular linked list
	func insert(_ value: Int)
	{
		// Create a new node
		let node: LinkNode? = LinkNode(value, self.head);
		if (self.head == nil)
		{
			// First node of linked list
			self.head = node;
			node!.next = self.head;
		}
		else
		{
			var temp: LinkNode? = self.head;
			// Find the last node
			while (!(temp!.next === self.head))
			{
				// Visit to next node
				temp = temp!.next;
			}
			// Add new node at the last 
			temp!.next = node;
		}
	}
	func countNode() -> Int
	{
		if (self.head == nil)
		{
			return 0;
		}
		// Start with second node
		var temp: LinkNode? = self.head!.next;
		// This is used to count linked node
		var count: Int = 1;
		// iterate circular linked list
		while (!(temp === self.head))
		{
			count += 1;
			// Visit to next node
			temp = temp!.next;
		}
		return count;
	}
	static func main(_ args: [String])
	{
		let cll: CircularLinkedList? = CircularLinkedList();
		// Add nodes
		cll!.insert(1);
		cll!.insert(3);
		cll!.insert(5);
		cll!.insert(7);
		cll!.insert(9);
		cll!.insert(11);
		// Display result
		print(cll!.countNode());
	}
}
CircularLinkedList.main([String]());

Output

6




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