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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://soumyajit4419.gitbook.io/ds-algo/linked-list/10.-swapping-nodes-in-a-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
