insert node at beginning of circular linked list in ruby

Ruby program for insert node at beginning of circular linked list. Here problem description and explanation.

#  Ruby Program 
#  Insert node at beginning of circular linked list

#  Define class of linked list Node
class LinkNode 
	# Define the accessor and reader of class LinkNode
	attr_reader :data, :next
	attr_accessor :data, :next
	def initialize(data, first) 
		self.data = data
		self.next = first
	end
end
class CircularLinkedList 
	# Define the accessor and reader of class CircularLinkedList
	attr_reader :head
	attr_accessor :head
	#  Class constructors
	def initialize() 
		self.head = nil
	end
	#  Insert node at begining of circular linked list
	def insert(value) 
		#  Create a node
		node = LinkNode.new(value, self.head)
		if (self.head == nil) 
			#  First node of linked list
			self.head = node
			node.next = self.head
		else
 
			temp = self.head
			#  Find the last node
			while (temp.next != self.head) 
				#  Visit to next node
				temp = temp.next
			end

			#  Add node
			temp.next = node
			#  make new head node
			self.head = node
		end

	end

	#  Display node element of circular linked list
	def display() 
		if (self.head == nil) 
			print("Empty Linked List\n")
		else
 
			print("  Linked List Element : \n")
			#  Get first node
			temp = self.head
			#  iterate linked list
			while (temp != nil) 
				#  Display node
				print("  ", temp.data)
				#  Visit to next node
				temp = temp.next
				if (temp == self.head) 
					#  Stop iteration
					return
				end

			end

		end

	end

end

def main() 
	task = CircularLinkedList.new()
	#  Add following linked list nodes
	task.insert(8)
	task.insert(7)
	task.insert(6)
	task.insert(5)
	task.insert(4)
	task.insert(3)
	task.insert(2)
	task.insert(1)
	#  Display node
	task.display()
end

main()

Output

  Linked List Element : 
  1  2  3  4  5  6  7  8


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