Skip to main content

Effectively insert node at beginning of circular linked list in swift

Swift program for Effectively insert node at beginning of circular linked list . Here more information.

import Foundation
// Swift 4 Program 
// Insert node at beginning of circular linked list
// Using head and tail nodes

// Define class of linked list Node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int, _ first: LinkNode? )
	{
		// Set node value
		self.data = data;
		self.next = first;
	}
}
class CircularLinkedList
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	// Insert node at begining of circular linked list
	func insert(_ value: Int)
	{
		// Create a node
		let node: LinkNode? = LinkNode(value, self.head);
		if (self.tail == nil)
		{
			// First node of linked list
			self.tail = node;
		}
		// Make new head
		self.head = node;
		// Connecting the last node to the top of the next field
		self.tail!.next = self.head;
	}
	// Display node element of circular linked list
	func display()
	{
		if (self.head == nil)
		{
			print("Empty Linked List");
		}
		else
		{
			print("Linked List Element :", terminator: "");
			var temp: LinkNode? = self.head;
			// iterate linked list
			while (temp  != nil)
			{
				// Display node
				print(" ",
					temp!.data, terminator: " ");
				if (temp === self.tail)
				{
					// Stop iteration
					// Or break;
					return;
				}
				// Visit to next node
				temp = temp!.next;
			}
		}
	}
	static func main(_ args: [String])
	{
		let task: CircularLinkedList? = CircularLinkedList();
		// Add following linked list nodes
		task!.insert(8);
		task!.insert(7);
		task!.insert(6);
		task!.insert(5);
		task!.insert(4);
		task!.insert(3);
		task!.insert(2);
		task!.insert(1);
		// Display node
		task!.display();
	}
}
CircularLinkedList.main([String]());

Output

Linked List Element :  1   2   3   4   5   6   7   8




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