Skip to main content

Find the smallest number in the doubly linked list in swift

Swift program for Find the smallest number in the doubly linked list. Here problem description and explanation.

import Foundation
// Swift 4 program for
// Find the smallest node in doubly linked list

// Linked List Node
class LinkNode
{
	var data: Int;
	var next: LinkNode? ;
	var prev: LinkNode? ;
	init(_ data: Int)
	{
		self.data = data;
		self.next = nil;
		self.prev = nil;
	}
}
class DoublyLinkedList
{
	var head: LinkNode? ;
	var tail: LinkNode? ;
	init()
	{
		self.head = nil;
		self.tail = nil;
	}
	// Insert new node at end position
	func insert(_ value: Int)
	{
		// Create a node
		let node: LinkNode? = LinkNode(value);
		if (self.head == nil)
		{
			// Add first node
			self.head = node;
			self.tail = node;
			return;
		}
		// Add node at last position
		self.tail!.next = node;
		node!.prev = self.tail;
		// new last node
		self.tail = node;
	}
	// Find smallest number
	func minNumber()
	{
		if (self.head == nil)
		{
			print("Empty Linked List");
		}
		else
		{
			// Get first node of linked list
			var temp: LinkNode? = self.head;
			var result: Int = temp!.data;
			// iterate linked list 
			while (temp  != nil)
			{
				if (temp!.data < result)
				{
					// Get new minimum
					result = temp!.data;
				}
				// Visit to next node
				temp = temp!.next;
			}
			print("Smallest : "
				+ String(result));
		}
	}
	static func main(_ args: [String])
	{
		let dll: DoublyLinkedList = DoublyLinkedList();
		// Insert following linked list nodes
		dll.insert(14);
		dll.insert(31);
		dll.insert(12);
		dll.insert(15);
		dll.insert(11);
		dll.insert(25);
		dll.minNumber();
	}
}
DoublyLinkedList.main([String]());

Output

Smallest : 11




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