# LeetCode - 1721. Swapping Nodes in a Linked List ### 題目網址:https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ ###### tags: `LeetCode` `Medium` `連結串列(Linked List)` ```cpp= /* -LeetCode format- Problem: 1721. Swapping Nodes in a Linked List Difficulty: Medium by Inversionpeter */ /** * 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) {} * }; */ static const auto Initialize = []{ ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: ListNode* swapNodes(ListNode* head, int k) { int length = 0, fromRight; ListNode *now = head, *target1 = nullptr, *target2 = nullptr; do { ++length; now = now->next; } while (now); fromRight = length - k + 1; now = head; for (int i = 1; i <= length; ++i) { if (i == k) target1 = now; if (i == fromRight) target2 = now; now = now->next; } swap(target1->val, target2->val); return head; } }; ```