Swapping Nodes in a Linked List

Medium Topics Company Tags

Swap the values stored in the kth node from the beginning and the kth node from the end of the linked list, then return its head. Count positions starting at 1 from either end. If both positions refer to the same node, the list is unchanged. Arrays in examples and test inputs list node values from head to tail.

Example 1:

Swapping Nodes in a Linked List, example 1: illustration of the example

Input: head = [2,4,6,8]
k = 1

Output: [8,4,6,2]

Explanation: The first node from the beginning contains 2, and the first from the end contains 8. Swap those values while leaving the two middle values unchanged.

Example 2:

Swapping Nodes in a Linked List, example 2: illustration of the example

Input: head = [5,1,9,3,7]
k = 2

Output: [5,3,9,1,7]

Explanation: The second node from the beginning contains 1, and the second from the end contains 3. Swapping them gives 5 -> 3 -> 9 -> 1 -> 7.

Example 3:

Swapping Nodes in a Linked List, example 3: illustration of the example

Input: head = [1,2,3]
k = 2

Output: [1,2,3]

Explanation: The second node from either end is the same middle node. Swapping its value with itself leaves the list unchanged.

Constraints:

  • The list contains n nodes, where 1 <= n <= 100000.
  • 1 <= k <= n
  • 0 <= Node.val <= 100


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.