Skip to main content

Find the smallest number in the doubly linked list in ruby

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

#  Ruby program for
#  Find the smallest node in doubly linked list

#  Linked List Node
class LinkNode 
	# Define the accessor and reader of class LinkNode
	attr_reader :data, :next, :prev
	attr_accessor :data, :next, :prev
	def initialize(data) 
		self.data = data
		self.next = nil
		self.prev = nil
	end

end

class DoublyLinkedList 
	# Define the accessor and reader of class DoublyLinkedList
	attr_reader :head, :tail
	attr_accessor :head, :tail
	def initialize() 
		self.head = nil
		self.tail = nil
	end

	#  Insert new node at end position
	def insert(value) 
		#  Create a node
		node = LinkNode.new(value)
		if (self.head == nil) 
			#  Add first node
			self.head = node
			self.tail = node
			return
		end

		#  Add node at last position
		self.tail.next = node
		node.prev = self.tail
		#  new last node
		self.tail = node
	end

	#  Find smallest number
	def minNumber() 
		if (self.head == nil) 
			print("Empty Linked List\n")
		else
 
			#  Get first node of linked list
			temp = self.head
			result = temp.data
			#  iterate linked list 
			while (temp != nil) 
				if (temp.data < result) 
					#  Get new minimum
					result = temp.data
				end

				#  Visit to next node
				temp = temp.next
			end

			print("Smallest : ", result, "\n")
		end

	end

end

def main() 
	dll = DoublyLinkedList.new()
	#  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()
end

main()

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