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