Sorted order insertion of linked list in ruby

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

#    Ruby program for
#    Add node in sorted order of linked list

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

end

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

	#  Add new node in sorted order
	def sortedAdd(data) 
		#  Create new node
		node = LinkNode.new(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
 
			temp = self.head
			#  Find position to add new node
			while (temp.next != nil && temp.next.data < data) 
				#  Visit to next node
				temp = temp.next
			end

			node.next = temp.next
			#  Add new node
			temp.next = node
		end

	end

	#  Display linked list element
	def display() 
		if (self.head == nil) 
			return
		end

		temp = self.head
		#  Iterating linked list elements
		while (temp != nil) 
			print(temp.data ," → ")
			#  Visit to next node
			temp = temp.next
		end

		print(" NULL\n")
	end

end

def main() 
	sll = SingleLL.new()
	#  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 \n")
	#  -7 → -3 → 1 → 4 → 9 → 11 → NULL
	sll.display()
end

main()

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