You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1700-1799/1721.Swapping Nodes in a Linked List/README_EN.md
+60-20
Original file line number
Diff line number
Diff line change
@@ -34,6 +34,12 @@
34
34
35
35
## Solutions
36
36
37
+
**Solution 1: Two Pointers**
38
+
39
+
We can first use a fast pointer `fast` to find the $k$th node of the linked list, and use a pointer `p` to point to it. Then, we use a slow pointer `slow` to start from the head node of the linked list, and move both pointers forward at the same time. When the fast pointer reaches the last node of the linked list, the slow pointer `slow` points to the $k$th node from the end of the linked list, and we use a pointer `q` to point to it. At this point, we only need to swap the values of `p` and `q`.
40
+
41
+
The time complexity is $O(n)$, where $n$ is the length of the linked list. The space complexity is $O(1)$.
0 commit comments