Skip to main content

Find out length of linked list in swift

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

import Foundation
// Swift 4 Program for
// Find the length of linked list 

// Linked list node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ value: Int)
	{
		self.data = value;
		self.next = nil;
	}
}
class SingleLL
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	// Insert new node at the last
	func insert(_ value: Int)
	{
		// Create new node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			self.head = node;
		}
		else
		{
			// Add new node at the end
			self.tail!.next = node;
		}
		self.tail = node;
	}
	// Count number of nodes and 
	// returns the number of nodes
	func findLength() -> Int
	{
		var temp: LinkNode? = self.head;
		var count: Int = 0;
		while (temp  != nil)
		{
			// Visit to next node
			temp = temp!.next;
			// Increase the node counter
			count += 1;
		}
		return count;
	}
	// Display all Linked List elements
	func display()
	{
		if (self.head  != nil)
		{
			print("Linked List Element", terminator: " : ");
			var temp: LinkNode? = self.head;
			while (temp  != nil)
			{
				print(temp!.data, terminator: "  ");
				temp = temp!.next;
			}
		}
		else
		{
			print("Empty Linked list");
		}
	}
	static func main(_ args: [String])
	{
		let task: SingleLL? = SingleLL();
		task!.insert(5);
		task!.insert(10);
		task!.insert(15);
		task!.insert(20);
		task!.insert(25);
		task!.insert(30);
		task!.insert(35);
		task!.display();
		print("\nLength :",task!.findLength());
	}
}
SingleLL.main([String]());

Output

Linked List Element : 5  10  15  20  25  30  35
Length : 7




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