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 2846071

Browse files
Update 0019.删除链表的倒数第N个节点.md
修改了0019.删除链表的倒数第N个节点 java 版本
1 parent 6de0c08 commit 2846071

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

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

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -87,30 +87,31 @@ public:
8787
java:
8888
8989
```java
90-
class Solution {
91-
public ListNode removeNthFromEnd(ListNode head, int n) {
92-
ListNode dummy = new ListNode(-1);
93-
dummy.next = head;
94-
95-
ListNode slow = dummy;
96-
ListNode fast = dummy;
97-
while (n-- > 0) {
98-
fast = fast.next;
99-
}
100-
// 记住 待删除节点slow 的上一节点
101-
ListNode prev = null;
102-
while (fast != null) {
103-
prev = slow;
104-
slow = slow.next;
105-
fast = fast.next;
106-
}
107-
// 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点
108-
prev.next = slow.next;
109-
// 释放 待删除节点slow 的next指针, 这句删掉也能AC
110-
slow.next = null;
90+
public ListNode removeNthFromEnd(ListNode head, int n){
91+
ListNode dummyNode = new ListNode(0);
92+
dummyNode.next = head;
93+
94+
//排除示例 2 的情况:head = [1], n = 1
95+
if (head == null)
96+
return null;
11197
112-
return dummy.next;
98+
ListNode fastIndex = dummyNode;
99+
ListNode slowIndex = dummyNode;
100+
101+
//只要快慢指针相差 n 个结点即可
102+
for (int i = 0; i < n ; i++){
103+
fastIndex = fastIndex.next;
104+
}
105+
106+
while (fastIndex.next != null){
107+
fastIndex = fastIndex.next;
108+
slowIndex = slowIndex.next;
113109
}
110+
111+
//此时 slowIndex 的位置就是待删除元素的前一个位置。
112+
//具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
113+
slowIndex.next = slowIndex.next.next;
114+
return dummyNode.next;
114115
}
115116
```
116117

0 commit comments

Comments
(0)

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