Skip to content

Commit 1f94655

Browse files
refactor: 优化0019.删除链表的倒数第N个节点.md
1 parent 3c9d6c4 commit 1f94655

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

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

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,12 @@
2222

2323
输入:head = [1,2,3,4,5], n = 2
2424
输出:[1,2,3,5]
25+
2526
示例 2:
2627

2728
输入:head = [1], n = 1
2829
输出:[]
30+
2931
示例 3:
3032

3133
输入:head = [1,2], n = 1
@@ -193,16 +195,18 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode {
193195
* @param {number} n
194196
* @return {ListNode}
195197
*/
196-
var removeNthFromEnd = function(head, n) {
197-
let ret = new ListNode(0, head),
198-
slow = fast = ret;
199-
while(n--) fast = fast.next;
200-
while (fast.next !== null) {
201-
fast = fast.next;
202-
slow = slow.next
203-
};
204-
slow.next = slow.next.next;
205-
return ret.next;
198+
var removeNthFromEnd = function (head, n) {
199+
// 创建哨兵节点,简化解题逻辑
200+
let dummyHead = new ListNode(0, head);
201+
let fast = dummyHead;
202+
let slow = dummyHead;
203+
while (n--) fast = fast.next;
204+
while (fast.next !== null) {
205+
slow = slow.next;
206+
fast = fast.next;
207+
}
208+
slow.next = slow.next.next;
209+
return dummyHead.next;
206210
};
207211
```
208212
### TypeScript:

0 commit comments

Comments
 (0)