Sorted order insertion of linked list in swift

Swift program for Sorted order insertion of linked list. Here problem description and explanation.

import Foundation
/*
    Swift 4 program for
    Add node in sorted order of linked list
*/
// Linked list node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
	}
}
class SingleLL
{
	var head: LinkNode? ;
	init()
	{
		self.head = nil;
	}
	// Add new node in sorted order
	func sortedAdd(_ data: Int)
	{
		// Create new node
		let node: LinkNode? = LinkNode(data);
		if (self.head == nil || 
          self.head!.data >= data)
		{
			// When linked list empty
			// or new nodes are adding at beginning
			node!.next = self.head;
			self.head = node;
		}
		else
		{
			var temp: LinkNode? = self.head;
			// Find position to add new node
			while (temp!.next  != nil && 
              temp!.next!.data < data)
			{
				// Visit to next node
				temp = temp!.next;
			}
			node!.next = temp!.next;
			// Add new node
			temp!.next = node;
		}
	}
	// Display linked list element
	func display()
	{
		if (self.head == nil)
		{
			return;
		}
		var temp: LinkNode? = self.head;
		// Iterating linked list elements
		while (temp  != nil)
		{
			print(temp!.data, terminator: " → ");
			// Visit to next node
			temp = temp!.next;
		}
		print("NULL");
	}
	static func main(_ args: [String])
	{
		let sll: SingleLL? = SingleLL();
		// Add Linked list node
		sll!.sortedAdd(1);
		sll!.sortedAdd(-3);
		sll!.sortedAdd(9);
		sll!.sortedAdd(4);
		sll!.sortedAdd(11);
		sll!.sortedAdd(-7);
		print("Linked List");
		// -7 → -3 → 1 → 4 → 9 → 11 → NULL
		sll!.display();
	}
}
SingleLL.main([String]());

Output

Linked List
-7 → -3 → 1 → 4 → 9 → 11 → NULL


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







© 2021, kalkicode.com, All rights reserved