All problems

Problem 384

Swap Kth Nodes from Both Ends

Medium · 20 pts · Linked List, Two Pointers

Problem

Swap the values of the K-th node from the beginning and the K-th node from the end of a linked list (both counted from 1), and print the list. If the two positions are the same node, the list does not change. Two pointers find both nodes in a single pass: move the first pointer K steps ahead, then advance both until the first reaches the end.

Input

First line: N and K. Second line: the N node values.

Output

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

Constraints

1 <= K <= N <= 100000; 0 <= value <= 100

Example input

5 2
1 2 3 4 5

Example output

1 4 3 2 5

Explanation

With K = 2 in 1 2 3 4 5, the 2nd node from the start holds 2 and the 2nd from the end holds 4. Swapping them gives 1 4 3 2 5.

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

Previous: Sort a Linked List Next: Maximum Twin Sum of a Linked List