Swap kth-from-end node with head
Swap k-th from End Node with Head in a Singly Linked List
Given the head of a singly linked list and an integer k, implement a function that swaps the k-th node from the end of the list with the head node.
Requirements:
- The swap must be performed by changing pointers, not by modifying node values.
- The solution must use O(1) extra memory.
- Assume
1 <= k <= n, wherenis the total number of nodes in the list. - If the k-th node from the end is already the head node (i.e.,
k == n), the list should remain unchanged, and the original head should be returned.
Examples:
Consider a list: 1 -> 2 -> 3 -> 4 -> 5 -> 6
- If
k = 1, the 1st node from the end is6. The new list should be6 -> 2 -> 3 -> 4 -> 5 -> 1. - If
k = 2, the 2nd node from the end is5. The new list should be5 -> 2 -> 3 -> 4 -> 1 -> 6. - If
k = 5, the 5th node from the end is2. The new list should be2 -> 1 -> 3 -> 4 -> 5 -> 6.
Return Value:
Return the new head of the modified linked list.
AI interview prep
Core dilemma
Correctly identifying and manipulating all relevant pointers (previous, current, next for both nodes involved) to perform the swap without breaking the list, especially when the nodes are adjacent or at the list's boundaries, all within O(1) space.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Swap kth-from-end node with head
Swap k-th from End Node with Head in a Singly Linked List
Given the head of a singly linked list and an integer k, implement a function that swaps the k-th node from the end of the list with the head node.
Requirements:
- The swap must be performed by changing pointers, not by modifying node values.
- The solution must use O(1) extra memory.
- Assume
1 <= k <= n, wherenis the total number of nodes in the list. - If the k-th node from the end is already the head node (i.e.,
k == n), the list should remain unchanged, and the original head should be returned.
Examples:
Consider a list: 1 -> 2 -> 3 -> 4 -> 5 -> 6
- If
k = 1, the 1st node from the end is6. The new list should be6 -> 2 -> 3 -> 4 -> 5 -> 1. - If
k = 2, the 2nd node from the end is5. The new list should be5 -> 2 -> 3 -> 4 -> 1 -> 6. - If
k = 5, the 5th node from the end is2. The new list should be2 -> 1 -> 3 -> 4 -> 5 -> 6.
Return Value:
Return the new head of the modified linked list.