The problem. Given the head of a linked list and a number k, swap the values of the kth node from the beginning and the kth node from the end (counting from 1). Return the head.
Input: head = [1, 2, 3, 4, 5], k = 2
Output: [1, 4, 3, 2, 5]
Input: head = [7, 9, 6, 6, 7, 8, 3, 0, 9, 5], k = 5
Output: [7, 9, 6, 6, 8, 7, 3, 0, 9, 5]Finding the kth node from the start is easy: walk k − 1 steps. The kth from the end is the tricky one, because a singly linked list can't walk backwards.
Free account
Sign up to read the rest of this lesson: 5 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come