Delete a node from linked list specific position in ruby

Ruby program for Delete a node from linked list specific position. Here problem description and explanation.

#  Ruby Program for
#  Delete node at given index 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, :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

	#  Delete node at given position
	def deleteAtIndex(index) 
		temp = self.head
		if (self.head == nil) 
			print("Empty linked list\n")
			return
		elsif (index < 0) 
			print("Invalid positions\n")
			return
		elsif (index == 1) 
			#  Means deleting a first node
			if (self.tail == self.head) 
				#  Only one node
				self.tail = nil
			end

			#  Make second node as head
			self.head = self.head.next
		else
 
			count = index - 1
			#  iterating linked list elements and find deleted node
			while (temp != nil && count > 1) 
				#  Visit to next node
				temp = temp.next
				count -= 1
			end

			if (count == 1 && temp.next != nil) 
				#  Get deleted node
				n = temp.next
				if (n == self.tail) 
					#  When delete last node
					self.tail = temp
				end

				#  Unlink the deleting node
				temp.next = n.next
			else
 
				print(" Index ", index ," are not present\n")
				return
			end

		end

	end

end

def main() 
	sll = SingleLL.new()
	#  Test with your index
	#  Note index start with 1
	index = 5
	#  Linked list
	#  10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → NULL
	sll.addNode(10)
	sll.addNode(20)
	sll.addNode(30)
	sll.addNode(40)
	sll.addNode(50)
	sll.addNode(60)
	sll.addNode(70)
	sll.addNode(80)
	print(" Before Delete Linked List\n")
	sll.display()
	#  Delete node at 5-th position
	sll.deleteAtIndex(index)
	#  Display linked list
	print(" After Delete Linked List\n")
	sll.display()
end

main()

Output

 Before Delete Linked List
10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → NULL
 After Delete Linked List
10 → 20 → 30 → 40 → 60 → 70 → 80 → 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