1、双指针做法
先求出链表长度,再分别找到要交换值的结点。
/**
* 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) {
int cnt=1;
ListNode* h1=head;
ListNode* h2=head;
while(h1->next!=NULL)
{
h1=h1->next;
++cnt;
}
if(cnt==1) return head;
h1=head;
for(int i=0;i<k-1;++i) h1=h1->next;
for(int i=0;i<cnt-k;++i) h2=h2->next;
cnt=h1->val;
h1->val=h2->val;
h2->val=cnt;
return head;
}
};