> For the complete documentation index, see [llms.txt](https://soumyajit4419.gitbook.io/ds-algo/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://soumyajit4419.gitbook.io/ds-algo/linked-list/10.-swapping-nodes-in-a-linked-list.md).

# 10. Swapping Nodes in a Linked List

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* `kth` *node from the beginning and the* `kth` *node from the end (the list is **1-indexed**).*

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg)

```
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:&#x20;

```cpp
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;
    }
};
```
