Skip to main content

Find largest node value of doubly linked list in swift

Swift program for Find largest node value of doubly linked list. Here problem description and other solutions.

import Foundation
// Swift 4 program for
// Find max value in doubly linked list

// Define class of 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 new 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;
		self.tail = node;
	}
	func maximum() -> Int
	{
		if (self.head == nil)
		{
			// When empty linked list
			return 0;
		}
		var result: Int = self.head!.data;
		// Get first node of linked list
		var temp: LinkNode? = self.head;
		// iterate linked list 
		while (temp  != nil)
		{
			if (temp!.data > result)
			{
				result = temp!.data;
			}
			// Visit to next node
			temp = temp!.next;
		}
		// Return maximum value
		return 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);
		print("Maximum  :",dll!.maximum());
	}
}
DoublyLinkedList.main([String]());

Output

Maximum  : 31




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