All problems

Problem 116

Partition List

Medium · 20 pts · Linked List, Two Pointers

Problem

You are given a linked list and a value X. Rearrange the list so that all nodes with values less than X come before all nodes with values greater than or equal to X. Inside each of the two groups, keep the nodes in their original relative order. Build two separate lists while walking through the original: one for the nodes below X and one for the rest, appending each node to the end of its list. Then attach the second list after the first.

Input

First line: integers N and X. Second line: the N node values (empty if N = 0).

Output

Print the node values of the resulting list from head to tail, space-separated, or EMPTY if it has no nodes.

Constraints

0 <= N <= 200; -100 <= value, X <= 100

Example input

6 3
1 4 3 2 5 2

Example output

1 2 2 4 3 5

Explanation

In 1 4 3 2 5 2 with X = 3, the values below 3 are 1, 2, 2 (in their original order) and the others are 4, 3, 5. Joining the two groups gives 1 2 2 4 3 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Remove Linked List Elements Next: Palindrome Linked List