[LeetCode] Swapping Nodes in a Linked List

1721. Swapping Nodes in a Linked List

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode* lastNode = head;
ListNode* target1 = head;
ListNode* target2 = head;

for(int i = 1; i < k; i++) {
lastNode = lastNode->next;
target1 = target1->next;
}

while(lastNode->next != nullptr) {
lastNode = lastNode->next;
target2 = target2->next;
}
swap(target1->val, target2->val);

return head;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/14/PS/LeetCode/swapping-nodes-in-a-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.