Python Program For Alternating Split Of A Given Singly Linked List- Set 1
Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists ‘a’ and ‘b’. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and the other should be 1->1->1.
Method (Simple):
The simplest approach iterates over the source list and pull nodes off the source and alternately put them at the front (or beginning) of ‘a’ and b’. The only strange part is that the nodes will be in the reverse order that occurred in the source list. Method 2 inserts the node at the end by keeping track of the last node in sublists.
Python
class Node:
def __init__( self , data,
next = None ):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def AlternatingSplit( self , a, b):
first = self .head
second = first. next
while (first is not None and
second is not None and
first. next is not None ):
self .MoveNode(a, first)
self .MoveNode(b, second)
first = first. next . next
if first is None :
break
second = first. next
def MoveNode( self , dest, node):
new_node = Node(node.data)
if dest.head is None :
dest.head = new_node
else :
new_node. next = dest.head
dest.head = new_node
def push( self , data):
new_node = Node(data)
new_node. next = self .head
self .head = new_node
def printList( self ):
temp = self .head
while temp:
print temp.data,
temp = temp. next
print ("")
if __name__ = = "__main__" :
llist = LinkedList()
a = LinkedList()
b = LinkedList()
llist.push( 5 )
llist.push( 4 )
llist.push( 3 )
llist.push( 2 )
llist.push( 1 )
llist.push( 0 )
llist.AlternatingSplit(a, b)
print "Original Linked List: " ,
llist.printList()
print "Resultant Linked List 'a' : " ,
a.printList()
print "Resultant Linked List 'b' : " ,
b.printList()
|
Output:
Original linked List: 0 1 2 3 4 5
Resultant Linked List 'a' : 4 2 0
Resultant Linked List 'b' : 5 3 1
Time Complexity: O(n) where n is a number of nodes in the given linked list.
Space Complexity: O(1),The time complexity for this algorithm is O(n) as we are traversing through the linked list only once.
Please refer complete article on Alternating split of a given Singly Linked List | Set 1 for more details!
Last Updated :
23 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...