imashutosh51

Odd Even Linked List

Oct 16th, 2022 (edited)
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. #     def __init__(self, val=0, next=None):
  4. #         self.val = val
  5. #         self.next = next
  6.  
  7. /*
  8. Logic:
  9. break the linked list into two halves ,one for the odd position and one for even positions.
  10. then join both of them.
  11. */
  12. class Solution:
  13.     def oddEvenList(self, head):
  14.         if not head or not head.next:
  15.             return head
  16.  
  17.         cur = head.next.next
  18.         odd_head = odd_tail = head
  19.         even_head = even_tail = head.next
  20.        
  21.         even_tail.next = None  # 🔥 break original chain
  22.         odd_tail.next = None
  23.         is_odd = True #because it is starting form the 3rd node
  24.        
  25.         while cur:
  26.             next_node = cur.next
  27.             cur.next = None
  28.            
  29.             if is_odd:
  30.                 odd_tail.next = cur
  31.                 odd_tail = cur
  32.             else:
  33.                 even_tail.next = cur
  34.                 even_tail = cur
  35.            
  36.             is_odd = not is_odd
  37.             cur = next_node
  38.        
  39.         odd_tail.next = even_head
  40.        
  41.         return odd_head
Advertisement
Add Comment
Please, Sign In to add comment