Delete middle node from linked list in ruby

Ruby program for Delete middle node from linked list. Here problem description and explanation.

#    Ruby program for
#    Delete middle node 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

	#  Adding new node at beginning of linked list
	def addNode(data) 
		#  Create new node
		node = LinkNode.new(data)
		#  Connect current node to previous head
		node.next = self.head
		self.head = node
	end

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

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

		print(" NULL\n")
	end

	#  Delete the middle node of linked list
	def deleteMid() 
		if (self.head == nil) 
			#  When linked list are no elements
			print("Empty Linked List", "\n")
		elsif (self.head.next == nil && 
               self.head.next.next == nil) 
			#  When linked list are less than  of 3 nodes
			print("Less then 3 node of linked list", "\n")
		else
 
			temp = self.head
			midPrevious = nil
			#  Find the middle and its previous node
			while (temp != nil && temp.next != nil && 
                   temp.next.next != nil) 
				if (midPrevious == nil) 
					#  When first node
					midPrevious = temp
				else
 
					#  Visit to next node
					midPrevious = midPrevious.next
				end

				#  Visit to next second next node
				temp = temp.next.next
			end

			#  Get the node which is deleting 
			temp = midPrevious.next
			#  Show deleted node
			print("Delete node : ", temp.data, "\n")
			#  Change link
			midPrevious.next = temp.next
		end

	end

end

def main() 
	sll = SingleLL.new()
	#  Linked list
	#  7 → 6 → 5 → 4 → 3 → 2 → 1 → NULL
	sll.addNode(1)
	sll.addNode(2)
	sll.addNode(3)
	sll.addNode(4)
	sll.addNode(5)
	sll.addNode(6)
	sll.addNode(7)
	print("Before Delete middle node", "\n")
	sll.display()
	#  Delete middle node
	sll.deleteMid()
	print("After Delete middle node", "\n")
	sll.display()
end

main()

Output

Before Delete middle node
7 → 6 → 5 → 4 → 3 → 2 → 1 →  NULL
Delete node : 4
After Delete middle node
7 → 6 → 5 → 3 → 2 → 1 →  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