328. Odd Even Linked List**

328. Odd Even Linked List**

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 ) O (1) space complexity and O ( n O d e s ) O(nodes) time complexity.

Example 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->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 …

C ++ implementation 1

A value regarding the position of the parity nodes are not dividing. Idea, two nodes oddand even, respectively, mount position and a position of an even odd nodes, and finally the evenchain mounted to oddthe back.

Use isOddodd or even node node determines whether the current node. Also note that the last to be set q->next = nullptr.

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head) return nullptr;
        ListNode *odd = new ListNode(0), *even = new ListNode(0);
        auto p = odd, q = even;
        bool isOdd = true;
        while (head) {
            if (isOdd) {
                p->next = head;
                p = p->next;
            }
            else {
                q->next = head;
                q = q->next;
            }
            head = head->next;
            isOdd = !isOdd;
        }
        q->next = nullptr; // 这一步不要忘了
        p->next = even->next;
        return odd->next;
    }
};

2 in C ++

Two years ago, the code reference https://leetcode.com/problems/odd-even-linked-list/solution/

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (!head || !head->next)
            return head;
        ListNode *odd = head, *even = head->next, *evenHead = even;
        // 这里没有设置虚拟头结点, 而是使用 head 来表示奇节点链表的头节点,
      	// evenHead 表示偶节点链表的头结点, 可以看到, 判断偶节点 even 以及
      	// next 是否存在让代码清晰很多.
        while (even && even->next) {
            odd->next = even->next;
            odd = odd->next;
            even->next = odd->next;
            even = even->next;
        }
        odd->next = evenHead;
        return head;
    }
};
Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104937197