328. Odd Even Linked List
Medium
Problem:
Reorganize the linked list so that the odd nodes come before the even nodes. Solve it with space complexity and time complexity .
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
https://leetcode.com/problems/odd-even-linked-list/
Solution:
The variables such as odd
, even
, and even_head
are always used consistently, regardless of the size of thus the space complexity also satisfies the constraint of .
Tip: The processing for odd and even can be bundled together into one multiple assignment.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return None
odd = head
even = head.next
even_head = head.next
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
odd.next = even_head
return head
Last updated