Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7502fc9

Browse files
Merge pull request youngyangyang04#2861 from chengxuanfu/master
添加19.删除链表的倒数第N个节点,添加了java方法使用递归的方法删除倒数第N个节点
2 parents 6a55e09 + 7a1d070 commit 7502fc9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎problems/0019.删除链表的倒数第N个节点.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,36 @@ class Solution {
129129
}
130130
```
131131

132+
133+
```java
134+
class Solution {
135+
public ListNode removeNthFromEnd(ListNode head, int n) {
136+
// 创建一个新的哑节点,指向原链表头
137+
ListNode s = new ListNode(-1, head);
138+
// 递归调用remove方法,从哑节点开始进行删除操作
139+
remove(s, n);
140+
// 返回新链表的头(去掉可能的哑节点)
141+
return s.next;
142+
}
143+
144+
public int remove(ListNode p, int n) {
145+
// 递归结束条件:如果当前节点为空,返回0
146+
if (p == null) {
147+
return 0;
148+
}
149+
// 递归深入到下一个节点
150+
int net = remove(p.next, n);
151+
// 如果当前节点是倒数第n个节点,进行删除操作
152+
if (net == n) {
153+
p.next = p.next.next;
154+
}
155+
// 返回当前节点的总深度
156+
return net + 1;
157+
}
158+
}
159+
```
160+
161+
132162
### Python:
133163

134164
```python

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /