---
# System prepended metadata

title: 1721. Swapping Nodes in a Linked List
tags: [leetcode]

---

# 1721. Swapping Nodes in a Linked List
###### tags: `leetcode`
## Description
You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

- Example 1:
![](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg)

>Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

- Example 2:

>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]

- Constraints:

>The number of nodes in the list is n.
1 <= k <= n <= 105
0 <= Node.val <= 100

## Solution
- The problem is constructed by ListNode, which is a Linked List. As the result, the true length and the nodes to swap value with is unknown.
- To make it easier, put everything into a vector and find the values to swap
```cpp=
for (ListNode* i = head; i != NULL; i = i->next) storage.push_back(i->val);
int temp = storage[k - 1];
storage[k - 1] = storage[storage.size() - k];
storage[storage.size() - k] = temp;
```
- Then iterate through all the nodes until two values are swapped and return it back
```cpp=
temp = max(k, int(storage.size()) + 1 - k);
ListNode* node = head;
for (int i = 0; i < temp; i++)
{
    if (i == k - 1 || i == storage.size() - k) node->val = storage[i];
    node = node->next;
}
return head;
```