Problem
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).
OR
Given a Linked List and a number k, Swap Kth Node from the front with the Kth Node from the End
Examples
Example 1:
--- title: Input List and k = 2 --- graph LR A1[1] --> B2[2]:::kth_node --> C3[3] --> D4[4] --> E5[5] classDef kth_node fill:#1E90FF,stroke:#000,stroke-width:2px;
--- title: Output List --- graph LR A1[1] --> D4[4]:::kth_node --> C3[3] --> B2[2]:::kth_node --> E5[5] classDef kth_node fill:#1E90FF,stroke:#000,stroke-width:2px;
|
|
Example 2:
--- title: Input List and k = 5 --- graph LR A7[7] --> B9[9] --> C6[6] --> D6[6] --> E7[7]:::kth_node --> F8[8] --> G3[3] --> H0[0] --> I9[9] --> J5[5] classDef kth_node fill:#1E90FF,stroke:#000,stroke-width:2px;
--- title: Output List --- graph LR A7[7] --> B9[9] --> C6[6] --> D6[6] --> F8[8]:::kth_node --> E7[7]:::kth_node --> G3[3] --> H0[0] --> I9[9] --> J5[5] classDef kth_node fill:#1E90FF,stroke:#000,stroke-width:2px;
|
|
Solution
Method 1 - Find the length of list
- Determine Length of the List: Traverse the list to determine its total length
n
. - Identify k-th Nodes:
- The
k
-th node from the beginning is straightforward. - The
k
-th node from the end is the(n - k + 1)
-th node from the beginning.
- The
- Swap Values: Swap the values of the identified nodes.
- Return the Modified List: Return the head of the modified linked list.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the linked list. We traverse the list multiple times, but each traversal is linear with respect to the number of nodes. - 🧺 Space complexity:
O(1)
, as we are using a constant amount of extra space for pointers and variables.