P14392 [GeeksforGeeks] Swap kth node from beginning and kth node from end in a singly linked list
普及
题目描述

Given a singly linked list of size N, and an integer K. You need to swap the K^{th} node from the beginning and K^{th} node from the end of the linked list. Swap the nodes through the links. Do not change the content of the nodes.

Example 1:
Input:
N = 4, K = 1
value[] = {1,2,3,4}
Output: 1
Explanation: Here K = 1, hence after
swapping the 1st node from the beginning
and end thenew list will be 4 2 3 1.

Example 2:
Input:
N = 5, K = 7
value[] = {1,2,3,4,5}
Output: 1
Explanation: K > N. Swapping is invalid.
Return the head node as it is.

Your Task:
You do not need to read input or print anything. The task is to complete the function swapkthnode(), which has takes head of link list, N and K as input parameters and returns the new head.
The generated output will be 1 if you are able to complete your task.

Expected Time Complexity: O(n)
Expected Auxillary space Complexity: O(1)

Constraints:
1 <= N <= 10^{3}
1 <= K <= 10^{3}

输入格式

见题面

输出格式

见题面

样例输入
N = 4, K = 1 value[] = {1,2,3,4}
样例输出
1