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 −

class Solution(object):
   def oddEvenList(self, head):
      :type head: ListNode
      :rtype: ListNode
      if head == None or head.next ==None:
         return 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




Published on 05-Feb-2020 10:43:34