Odd Even Linked List in Python


Suppose we have a singly linked list, we have to group all odd nodes together followed by the even nodes. Here we are talking about the node position not the value in the nodes. We should try to do it in place. So if the nodes are [1,22,13,14,25], the result will be [1,13,25,22,14]

To solve this, we will follow these steps −

  • if head is null or the next of head is null, then return head
  • head1 := head, head2 := next of head, head_beg := next of head
  • while next of head2 is nor null and next of (next of head is not null)
    • next of head1 := next of head2
    • next of head2 = next of (next of head)
    • head1 := next of head1 and head2 := next of head2
  • if next of head2 is not null
    • next of head1 := next of head2
    • head1 := next of head1
  • next of head1 := head2_beg and next of head2 = null
  • return head

Let us see the following implementation to get better understanding −

Example

 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
      while ptr.next:
         ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution(object):
   def oddEvenList(self, head):
      if head == None or head.next ==None:
         return head
      head1=head
      head2,head2_beg= head.next,head.next
      while head2.next!= None and head2.next.next!= None:
         head1.next = head2.next
         head2.next = head2.next.next
         head1 = head1.next
         head2 = head2.next
      if head2.next!=None:
         head1.next = head2.next
         head1 = head1.next
      head1.next = head2_beg
      head2.next = None
      return head
ob1 = Solution()
head = make_list([1,22,13,14,25])
print_list(ob1.oddEvenList(head))

Input

[1,22,13,14,25]

Output

[1, 13, 25, 22, 14, ]

Updated on: 04-May-2020

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements