https://leetcode.cn/problems/swapping-nodes-in-a-linked-list/description/
这道题我们可以通过两个循环来找到链表正数第k个节点和倒数第k个节点。
struct ListNode* swapNodes(struct ListNode* head, int k) {
int len = 0;
struct ListNode* cur = head;
while(cur)
{
++len;
cur = cur->next;
}
cur = head;
for(int i=1 ; i < k ; i++)
{
cur = cur->next;
}
struct ListNode* tail = head;
for(int i = 1 ; i < len-k+1 ; i++)
{
tail = tail->next;
}
int tmp = cur->val;
cur->val = tail->val;
tail->val = tmp;
return head;
}