Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]
Input: head = [1], k = 1
Output: [1]
Input: head = [1,2], k = 1
Output: [2,1]
Input: head = [1,2,3], k = 2
Output: [1,2,3]
class Solution
{
public:
int getLen(ListNode *head)
{
int count = 0;
ListNode *p = head;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
ListNode *swapNodes(ListNode *head, int k)
{
if(head == NULL){
return head;
}
int l = getLen(head);
int f = 1;
ListNode *p = head;
while (f < k)
{
p = p->next;
f++;
}
ListNode *q = head;
int b = l - k + 1;
int x = 1;
while (x < b)
{
q = q->next;
x++;
}
swap(p->val, q->val);
return head;
}
};