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: lcci/02.02.Kth Node From End of List/README_EN.md
+46-9
Original file line number
Diff line number
Diff line change
@@ -22,7 +22,11 @@
22
22
23
23
## Solutions
24
24
25
-
### Solution 1
25
+
### Solution 1: Two Pointers
26
+
27
+
We define two pointers `slow` and `fast`, both initially pointing to the head node `head`. Then the `fast` pointer moves forward $k$ steps first, and then the `slow` and `fast` pointers move forward together until the `fast` pointer points to the end of the list. At this point, the node pointed to by the `slow` pointer is the $k$-th node from the end of the list.
28
+
29
+
The time complexity is $O(n)$, where $n$ is the length of the list. The space complexity is $O(1)$.
26
30
27
31
<!-- tabs:start -->
28
32
@@ -40,7 +44,8 @@ class Solution:
40
44
for _ inrange(k):
41
45
fast = fast.next
42
46
while fast:
43
-
slow, fast = slow.next, fast.next
47
+
slow = slow.next
48
+
fast = fast.next
44
49
return slow.val
45
50
```
46
51
@@ -82,7 +87,7 @@ public:
82
87
int kthToLast(ListNode* head, int k) {
83
88
ListNode* fast = head;
84
89
ListNode* slow = head;
85
-
while (k-- > 0) {
90
+
while (k--) {
86
91
fast = fast->next;
87
92
}
88
93
while (fast) {
@@ -95,9 +100,16 @@ public:
95
100
```
96
101
97
102
```go
103
+
/**
104
+
* Definition for singly-linked list.
105
+
* type ListNode struct {
106
+
* Val int
107
+
* Next *ListNode
108
+
* }
109
+
*/
98
110
func kthToLast(head *ListNode, k int) int {
99
111
slow, fast := head, head
100
-
for i := 0; i < k; i++ {
112
+
for ; k > 0; k-- {
101
113
fast = fast.Next
102
114
}
103
115
for fast != nil {
@@ -108,6 +120,32 @@ func kthToLast(head *ListNode, k int) int {
0 commit comments