Remove every k th node of the linked list in ruby

Ruby program for Remove every k th node of the linked list. Here problem description and explanation.

#  Ruby Program for
#  delete every k-th node of the 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 at the end of linked list
	def addNode(value) 
		#  Create  node
		node = LinkNode.new(value)
		if (self.head == nil) 
			self.head = node
		else
 
			temp = self.head
			#  Find last node
			while (temp.next != nil) 
				#  Visit to next node
				temp = temp.next
			end

			#  Add node at last position
			temp.next = node
		end

	end

	#  Display all Linked List elements
	def display() 
		if (self.head != nil) 
			temp = self.head
			while (temp != nil) 
				#  Display node value
				print("  ", temp.data)
				#  Visit to next node
				temp = temp.next
			end

		else
 
			print("Empty Linked list\n")
		end

	end

	def removeKh(kth) 
		if (self.head == nil) 
			#  When no element
			print("Empty Linked list\n")
		elsif (kth <= 0) 
			print("\nInvalid position ", kth, "\n")
		else
 
			temp = self.head
			hold = nil
			checker = nil
			count = 0
			if (kth == 1) 
				#  When delete all element
				self.head = nil
			end

			while (temp != nil) 
				count += 1
				if (count % kth == 0) 
					#  When delete node found
					hold = temp
				else
 
					#  Get current node
					checker = temp
				end

				temp = temp.next
				#  When get free node
				if (hold != nil) 
					if (checker != nil) 
						#  Unlink node
						checker.next = hold.next
					end

					hold = nil
				end

			end

		end

	end

end

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

main()

Output

Position : 2
Before Delete Linked List
  1  2  3  4  5  6  7
 After Linked List
  1  3  5  7


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