Delete duplicate nodes from sorted linked list in ruby

Ruby program for Delete duplicate nodes from sorted linked list. Here problem description and explanation.

#    Ruby program for
#    Delete duplicate nodes in sorted 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, :tail
	attr_accessor :head, :tail
	def initialize() 
		self.head = nil
		self.tail = nil
	end

	#  Add new node at the end of linked list
	def addNode(value) 
		#  Create a new node
		node = LinkNode.new(value)
		if (self.head == nil) 
			self.head = node
		else
			self.tail.next = node
		end

		self.tail = node
	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

	#  Remove the duplicate nodes from sorted singly linked list
	def deleteDuplicate() 
		if (self.head == nil) 
			return
		else
 
			#  Auxiliary variables
			temp = self.head.next
			current = self.head
			hold = nil
			#  Find and remove duplicate
			while (temp != nil) 
				#  Check duplicate node 
				if (current.data == temp.data) 
					#   When node key are same
					hold = temp
				else
 
					#  When node key are not same
					current = temp
				end

				#  Visit to next node
				temp = temp.next
				if (hold != nil) 
					#  Modified link value
					current.next = temp
					hold = nil
				else
 
					#  Change last node
					self.tail = current
				end

			end

		end

	end

end

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

main()

Output

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