Skip to main content

Alternating split of singly linked list in python

Python program for Alternating split of singly linked list. Here problem description and explanation.

#  Python 3 program for
#  Alternating split of a given singly linked list

#  Node of LinkedList
class LinkNode :
	def __init__(self, data) :
		#  Set node value
		self.data = data
		self.next = None
	

class MyLinkedList :
	def __init__(self) :
		self.head = None
	
	#  Add new node at the end of linked list
	def insert(self, value) :
		#  Create a new node
		node = LinkNode(value)
		if (self.head == None) :
			self.head = node
		else :
			temp = self.head
			#  Find last node
			while (temp.next != None) :
				#  Visit to next node
				temp = temp.next
			
			#  Add node at last position
			temp.next = node
		
	
	#  Display all Linked List elements
	def display(self) :
		if (self.head != None) :
			temp = self.head
			while (temp != None) :
				#  Display node value
				print(temp.data, end = "  ")
				#  Visit to next node
				temp = temp.next
			
		else :
			print("Empty Linked list")
		
	
	#  Split the linked list by alternating nodes
	def splitting(self) :
		result = None
		if (self.head != None) :
			#  Some auxiliary variables
			temp = self.head
			tail = None
			current = None
			prev = self.head
			while (temp != None and temp.next != None) :
				current = temp.next
				prev = temp
				temp = temp.next.next
				if (result == None) :
					#  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
				
				prev.next = temp
			
		
		return result
	

def main() :
	l1 = MyLinkedList()
	l2 = MyLinkedList()
	#  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 : ", end = "")
	l1.display()
	l2.head = l1.splitting()
	print("\nAfter splitting ")
	print("L1 list : ", end = "")
	l1.display()
	print("\nL2 list : ", end = "")
	l2.display()

if __name__ == "__main__": 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