You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kthnode from the beginning and the kthnode from the end (the list is 1-indexed).
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]
Example 2:
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]
Example 3:
Input: head = [1], k = 1
Output: [1]
Example 4:
Input: head = [1,2], k = 1
Output: [2,1]
Example 5:
Input: head = [1,2,3], k = 2
Output: [1,2,3]
Solution:
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;
}
};