328.Odd Even Linked List

Tags: [linked_list], [list], [prev_curr_pointers]

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

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:
Given1->2->3->4->5->NULL,
return1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...


Solution: prev curr pointer

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        even_list_fake_head = ListNode(-1)
        even_list_curr = even_list_fake_head

        prev = None
        curr = head
        counter = 1

        while curr is not None:
            if counter % 2 == 1:
                prev = curr
                curr = curr.next
            else:
                prev.next = curr.next
                even_list_curr.next = curr
                even_list_curr = even_list_curr.next
                curr = curr.next
                even_list_curr.next = None

            counter += 1

        prev.next = even_list_fake_head.next
        return head

Revelation:

  • The reason we must do "curr = curr.next" before the "even_list_curr.next = None" is that we should first use the bridge curr -> curr.next to update the curr for next iteration, then we can cut this bridge.

Note:

  • Time complexity = O(n), n is the number of nodes in the given list.
  • Space complexity = O(1).

results matching ""

    No results matching ""