O(n)
注意点k可能大于 n / 2即可
/** * 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* p = head; int cnt = 1, flag = 0; ListNode* q = nullptr, *r = nullptr; int n = 0; while(p) { n++; p = p->next; } p = head; if(k > n / 2) k = n - k + 1; while(p->next) { if(cnt == k) { q = p; r = head; flag = 1; } if(flag) r = r->next, p = p->next; else p = p->next; cnt++; } if(p == head) return head; int tmp = q->val; q->val = r->val; r->val = tmp; return head; } };