Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Linked List

Segregate Even and Odd Nodes

Easy · Linked List · Asked at Amazon, Microsoft, TCS, Infosys

Rearrange the list so that all nodes with even values come first, followed by all nodes with odd values. Keep the original relative order inside each group. Print the list.

Input

First line: n. Second line: the n node values from head to tail.

Output

The rearranged list, space-separated.

Constraints

Build two chains while walking the list — one for even values, one for odd — then attach the odd chain after the even chain. Remember to end the odd chain with null.

Example 1

Input

7
17 15 8 9 2 4 6

Output

8 2 4 6 17 15 9

Example 2

Input

3
1 3 5

Output

1 3 5

Hints

  1. Split the nodes into two chains as you walk: evens and odds.
  2. Dummy heads make appending to an empty chain easy.
  3. Join the even chain to the odd chain, and end the odd chain with null.

Approach

Walk once. Append each node to the tail of the even chain or the odd chain depending on its value — the original order inside each chain is kept automatically. Finally link evenTail.next = oddHead and oddTail.next = null (otherwise the last odd node may still point into the old list and create a loop).

Complexity: O(n) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

struct Node {
    long long val;
    Node *next = nullptr;
    Node(long long v) : val(v) {}
};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    Node dummy(0), *t = &dummy;
    for (int i = 0; i < n; i++) {
        long long x;
        cin >> x;
        t = t->next = new Node(x);
    }
    Node evenHead(0), oddHead(0), *e = &evenHead, *o = &oddHead;
    for (Node *p = dummy.next; p; p = p->next) {
        if (p->val % 2 == 0) e = e->next = p;
        else o = o->next = p;
    }
    o->next = nullptr;
    e->next = oddHead.next;
    for (Node *p = evenHead.next; p; p = p->next) cout << p->val << (p->next ? " " : "\n");
    return 0;
}

Python solution

import sys


class Node:
    def __init__(self, val):
        self.val, self.next = val, None


data = list(map(int, sys.stdin.read().split()))
dummy = tail = Node(0)
for v in data[1 : 1 + data[0]]:
    tail.next = Node(v)
    tail = tail.next
even_head, odd_head = Node(0), Node(0)
e, o = even_head, odd_head
p = dummy.next
while p:
    if p.val % 2 == 0:
        e.next = p
        e = p
    else:
        o.next = p
        o = p
    p = p.next
o.next = None
e.next = odd_head.next
out, p = [], even_head.next
while p:
    out.append(p.val)
    p = p.next
print(*out)

Java solution

import java.io.*;

public class Main {
    static class Node {
        long val;
        Node next;
        Node(long v) { val = v; }
    }

    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        Node dummy = new Node(0), t = dummy;
        for (int i = 0; i < n; i++) {
            in.nextToken();
            t = t.next = new Node((long) in.nval);
        }
        Node evenHead = new Node(0), oddHead = new Node(0), e = evenHead, o = oddHead;
        for (Node p = dummy.next; p != null; p = p.next) {
            if (p.val % 2 == 0) e = e.next = p;
            else o = o.next = p;
        }
        o.next = null;
        e.next = oddHead.next;
        StringBuilder sb = new StringBuilder();
        for (Node p = evenHead.next; p != null; p = p.next) sb.append(p.val).append(p.next != null ? " " : "\n");
        System.out.print(sb);
    }
}

Solve Segregate Even and Odd Nodes online · All practice problems