Getting everything ready for you…

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

0s

Practice › Linked List

Partition a List Around X

Medium · Linked List · Asked at Amazon, Microsoft, Adobe, Bloomberg

Rearrange the list so that every node with a value less than x comes before every node with a value greater than or equal to x. Keep the original relative order inside both parts. Print the list.

Input

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

Output

The partitioned list, space-separated.

Constraints

Two dummy heads: append each node to the "less" chain or the "rest" chain, then join them and end the rest chain with null.

Example 1

Input

6
1 4 3 2 5 2
3

Output

1 2 2 4 3 5

Example 2

Input

2
2 1
2

Output

1 2

Hints

  1. Build two separate chains: nodes < x and nodes ≥ x.
  2. Appending to the tail of each chain keeps the original order.

Approach

Use two dummy heads, "less" and "rest". Walk the list once and append each node to the matching chain. Then connect lessTail.next = restHead.next and set restTail.next = null — the last node of the rest chain may still point to a node that was moved to the less chain.

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 v;
        cin >> v;
        t = t->next = new Node(v);
    }
    long long x;
    cin >> x;
    Node lessHead(0), restHead(0), *a = &lessHead, *b = &restHead;
    for (Node *p = dummy.next; p; p = p->next) {
        if (p->val < x) a = a->next = p;
        else b = b->next = p;
    }
    b->next = nullptr;
    a->next = restHead.next;
    for (Node *p = lessHead.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()))
n = data[0]
dummy = tail = Node(0)
for v in data[1 : 1 + n]:
    tail.next = Node(v)
    tail = tail.next
x = data[1 + n]
less_head, rest_head = Node(0), Node(0)
a, b = less_head, rest_head
p = dummy.next
while p:
    if p.val < x:
        a.next = p
        a = p
    else:
        b.next = p
        b = p
    p = p.next
b.next = None
a.next = rest_head.next
out, p = [], less_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);
        }
        in.nextToken();
        long x = (long) in.nval;
        Node lessHead = new Node(0), restHead = new Node(0), a = lessHead, b = restHead;
        for (Node p = dummy.next; p != null; p = p.next) {
            if (p.val < x) a = a.next = p;
            else b = b.next = p;
        }
        b.next = null;
        a.next = restHead.next;
        StringBuilder sb = new StringBuilder();
        for (Node p = lessHead.next; p != null; p = p.next) sb.append(p.val).append(p.next != null ? " " : "\n");
        System.out.print(sb);
    }
}

Solve Partition a List Around X online · All practice problems