Skip to main content

Alternating split of singly linked list in ruby

Ruby program for Alternating split of singly linked list. Here more information.

#  Ruby program for
#  Alternating split of a given singly linked list

#  Node of LinkedList
class LinkNode 
	# Define the accessor and reader of class LinkNode
	attr_reader :data, :next
	attr_accessor :data, :next
	def initialize(data) 
		#  Set node value
		self.data = data
		self.next = nil
	end

end

class MyLinkedList 
	# Define the accessor and reader of class MyLinkedList
	attr_reader :head
	attr_accessor :head
	def initialize() 
		self.head = nil
	end

	#  Add new node at the end of linked list
	def insert(value) 
		#  Create a new 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

	#  Split the linked list by alternating nodes
	def splitting() 
		result = nil
		if (self.head != nil) 
			#  Some auxiliary variables
			temp = self.head
			tail = nil
			current = nil
			prev = self.head
			while (temp != nil && temp.next != nil) 
				current = temp.next
				prev = temp
				temp = temp.next.next
				if (result == nil) 
					#  When first node of second linked list
					current.next = result
					result = current
					tail = current
				else
 
					#  Add Alternating node to end of 
					#  second linked list
					current.next = tail.next
					tail.next = current
					tail = current
				end

				prev.next = temp
			end

		end

		return result
	end

end

def main() 
	l1 = MyLinkedList.new()
	l2 = MyLinkedList.new()
	#  Add node in l1 linked list
	l1.insert(1)
	l1.insert(2)
	l1.insert(3)
	l1.insert(4)
	l1.insert(5)
	l1.insert(6)
	l1.insert(7)
	l1.insert(8)
	#  Before splitting l1
	print("L1 list : ")
	l1.display()
	l2.head = l1.splitting()
	print("\nAfter splitting \n")
	print("L1 list : ")
	l1.display()
	print("\nL2 list : ")
	l2.display()
end

main()

Output

L1 list :   1  2  3  4  5  6  7  8
After splitting 
L1 list :   1  3  5  7
L2 list :   2  4  6  8




Comment

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