Advertisement
vb8188

even odd linked list solution

Sep 27th, 2021 (edited)
1,127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, value, next=None):
  3.         self.value = value
  4.         self.next = next
  5.     def __str__(self):
  6.         curr = self
  7.         output = ''
  8.         while curr:
  9.             output += str(curr.value)
  10.             curr = curr.next
  11.         return output
  12.  
  13. def list_to_linkedlist(list):
  14.     n = Node(list[0])
  15.     head = n
  16.     for i in list[1:]:
  17.         n.next = Node(i)
  18.         n = n.next
  19.     return head
  20.  
  21. def delete_node(node,value):
  22.     current = node
  23.     prev = None
  24.     next = current.next
  25.     while current.next:
  26.         if current.value != value:  
  27.             prev = current
  28.             current = current.next
  29.             next = current.next
  30.         else:
  31.             prev.next = current.next
  32.             break
  33.     return node
  34.  
  35. def create_odd_even_ll(node):
  36.     index = 0
  37.     ell = None
  38.     oll = None
  39.     while node:
  40.         if index%2 == 0 and not ell:
  41.             ell = Node(node.value)
  42.             ell_head = ell
  43.         elif index%2 != 0 and not oll:
  44.             oll = Node(node.value)
  45.             oll_head = oll
  46.         elif index%2 == 0 and ell:
  47.             ell.next = Node(node.value)
  48.             ell = ell.next
  49.         elif index%2 != 0 and oll:
  50.             oll.next = Node(node.value)
  51.             oll = oll.next
  52.         index += 1    
  53.         node = node.next
  54.     ell.next = oll_head
  55.     return ell_head
  56. if __name__ == "__main__":
  57.     list = [1,2,3,4,5,6]
  58.     x = list_to_linkedlist(list)
  59.     print(create_odd_even_ll(x))
  60.  
  61. ➜  TechDev python linked_list.py
  62. 135246
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement