Skip to content

Latest commit

 

History

History
85 lines (61 loc) · 3.11 KB

File metadata and controls

85 lines (61 loc) · 3.11 KB

328. Odd Even Linked List (Medium)

Date and Time: Oct 24, 2024, 23:16 (EST)

Link: https://leetcode.com/problems/odd-even-linked-list/


Question:

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.


Example 1:

Input: head = [1,2,3,4,5]

Output: [1,3,5,2,4]

Example 2:

Input: head = [2,1,3,5,6,4,7]

Output: [2,3,6,7,1,5,4]


Constraints:

  • The number of nodes in the linked list is in the range [0, 10^4].

  • -10^6 <= Node.val <= 10^6


Walk-through:

Create two separate head odd, even to create two linked-list, and then we add the even linked-list to the end of odd.


Python Solution:

# 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]:
        # Create two heads to save odd and even linkedlist
        # repeatedly update both linkedlist until even or even.next is none
        # Finally, add the even linkedlist to the end of odd linkedlist

        # TC: O(n), SC: O(1)
        if not head:
            return None
        # odd, even ptr
        odd = head
        even = evenHead = head.next
        while even and even.next:
            # Update odd linked-list
            odd.next = odd.next.next
            odd = odd.next
            # Update even linked-list
            even.next = even.next.next
            even = even.next
        # connect even linkedlist in the end
        odd.next = evenHead

        return head

Time Complexity: $O(n)$
Space Complexity: $O(1)$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms