Segregate even and odd nodes in sorted order in python

Python program for Segregate even and odd nodes in sorted order. Here problem description and explanation.

``````#  Python 3 program for
#  Segregate even and odd nodes in ascending order

#  Linked list node
def __init__(self, data) :
self.data = data
self.next = None

class SingleLL :
def __init__(self) :

#  Add new node at the end of linked list
def insert(self, value) :
#  Create  node
if (self.head == None) :
else :
#  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) :
while (temp != None) :
#  Display node value
print(" ", temp.data, end = " ")
#  Visit to next node
temp = temp.next

else :

def sortedAdd(self, element) :
if (self.head == None) :
elif (self.head.data >= element.data) :
else :
#  Finding location of inserting node
while (temp.next != None and
temp.next.data < element.data) :
#  Visit to next node
temp = temp.next

element.next = temp.next
temp.next = element

def segregateNode(self, odd, even) :
node = None
#  Iterating the linked list node
while (self.head != None) :
#  Visit to next node
#  Set null to next node
node.next = None
if (node.data % 2 == 0) :
#  When node value is Even
else :
#  When node value is Odd

def main() :
#  Create linked lists
sll = SingleLL()
odd = SingleLL()
even = SingleLL()
#  Linked list sll
#  4 → 3 → 5 → 2 → 11 → 1 → 6 → NULL
sll.insert(4)
sll.insert(3)
sll.insert(5)
sll.insert(2)
sll.insert(11)
sll.insert(1)
sll.insert(6)
print("Initial Element")
#  Display all node
sll.display()
sll.segregateNode(odd, even)
print("\nEven Element")
#  Display all even node
even.display()
print("\nOdd Element")
#  Display all odd node
odd.display()

if __name__ == "__main__": main()``````

Output

``````Initial Element
4   3   5   2   11   1   6
Even Element
2   4   6
Odd Element
1   3   5   11``````

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.