Skip to content

Commit e59f746

Browse files
committed
feat: add python and java solutions to lcci problem
添加《程序员面试金典》题解:面试题 02.02. 返回倒数第 k 个节点
1 parent 17ec379 commit e59f746

File tree

3 files changed

+103
-0
lines changed

3 files changed

+103
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# [面试题 02.02. 返回倒数第 k 个节点](https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/)
2+
3+
## 题目描述
4+
实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。
5+
6+
**注意:** 本题相对原题稍作改动
7+
8+
**示例:**
9+
10+
```
11+
输入: 1->2->3->4->5 和 k = 2
12+
输出: 4
13+
```
14+
15+
**说明:**
16+
17+
- 给定的 k 保证是有效的。
18+
19+
## 解法
20+
### Python3
21+
```python
22+
# Definition for singly-linked list.
23+
# class ListNode:
24+
# def __init__(self, x):
25+
# self.val = x
26+
# self.next = None
27+
28+
class Solution:
29+
def kthToLast(self, head: ListNode, k: int) -> int:
30+
p = q = head
31+
for _ in range(k):
32+
q = q.next
33+
while q:
34+
q = q.next
35+
p = p.next
36+
return p.val
37+
```
38+
39+
### Java
40+
```java
41+
/**
42+
* Definition for singly-linked list.
43+
* public class ListNode {
44+
* int val;
45+
* ListNode next;
46+
* ListNode(int x) { val = x; }
47+
* }
48+
*/
49+
class Solution {
50+
public int kthToLast(ListNode head, int k) {
51+
ListNode p = head, q = head;
52+
while (k-- > 0) {
53+
q = q.next;
54+
}
55+
while (q != null) {
56+
q = q.next;
57+
p = p.next;
58+
}
59+
return p.val;
60+
}
61+
}
62+
```
63+
64+
### ...
65+
```
66+
67+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) { val = x; }
7+
* }
8+
*/
9+
class Solution {
10+
public int kthToLast(ListNode head, int k) {
11+
ListNode p = head, q = head;
12+
while (k-- > 0) {
13+
q = q.next;
14+
}
15+
while (q != null) {
16+
q = q.next;
17+
p = p.next;
18+
}
19+
return p.val;
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution:
8+
def kthToLast(self, head: ListNode, k: int) -> int:
9+
p = q = head
10+
for _ in range(k):
11+
q = q.next
12+
while q:
13+
q = q.next
14+
p = p.next
15+
return p.val

0 commit comments

Comments
 (0)