mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
refactor: 优化0019.删除链表的倒数第N个节点.md
This commit is contained in:
@ -22,10 +22,12 @@
|
||||
|
||||
输入:head = [1,2,3,4,5], n = 2
|
||||
输出:[1,2,3,5]
|
||||
|
||||
示例 2:
|
||||
|
||||
输入:head = [1], n = 1
|
||||
输出:[]
|
||||
|
||||
示例 3:
|
||||
|
||||
输入:head = [1,2], n = 1
|
||||
@ -194,15 +196,17 @@ func removeNthFromEnd(head *ListNode, n int) *ListNode {
|
||||
* @return {ListNode}
|
||||
*/
|
||||
var removeNthFromEnd = function (head, n) {
|
||||
let ret = new ListNode(0, head),
|
||||
slow = fast = ret;
|
||||
// 创建哨兵节点,简化解题逻辑
|
||||
let dummyHead = new ListNode(0, head);
|
||||
let fast = dummyHead;
|
||||
let slow = dummyHead;
|
||||
while (n--) fast = fast.next;
|
||||
while (fast.next !== null) {
|
||||
slow = slow.next;
|
||||
fast = fast.next;
|
||||
slow = slow.next
|
||||
};
|
||||
}
|
||||
slow.next = slow.next.next;
|
||||
return ret.next;
|
||||
return dummyHead.next;
|
||||
};
|
||||
```
|
||||
### TypeScript:
|
||||
|
Reference in New Issue
Block a user