Delete last node of linked list in ruby

Ruby program for Delete last node of linked list. Here problem description and explanation.

#    Ruby program for
#    Delete the last node of singly 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

		#  Set new last node
		self.tail = node
	end

	#  Display linked list element
	def display() 
		if (self.head == nil) 
			print("Empty Linked List\n")
			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 last node of singly linked list
	def deleteLastNode() 
		if (self.head == nil) 
			print("Empty Linked List\n")
			return
		else
 
			temp = self.head
			find = nil
			#  Find second last node
			while (temp.next != nil) 
				find = temp
				temp = temp.next
			end

			if (find == nil) 
				#  Delete head node of linked list
				self.head = nil
				self.tail = nil
			else
 
				#  Set new last node
				self.tail = find
				find.next = nil
			end

		end

	end

end

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

main()

Output

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