Insert node at beginning of doubly linked list in ruby

Ruby program for Insert node at beginning of doubly linked list. Here problem description and other solutions.

#  Ruby Program For
#  insert new node at beginning of doubly linked list

#  Define class of 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
	attr_accessor :head
	def initialize() 
		self.head = nil
	end
	#  Insert new node at beginning position
	def insert(value) 
		#  Create a node
		node = LinkNode.new(value)
		node.next = self.head
		#  When linked list is not empty
		if (self.head != nil) 
			self.head.prev = node
		end
		#  Make new head
		self.head = node
	end

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

		end

	end

end

def main() 
	dll = DoublyLinkedList.new()
	#  Insert following linked list nodes
	dll.insert(70)
	dll.insert(60)
	dll.insert(50)
	dll.insert(40)
	dll.insert(30)
	dll.insert(20)
	dll.insert(10)
	#   NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	dll.display()
end

main()

Output

  Doubly Linked List Element :
  10  20  30  40  50  60  70


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