0019._Remove_Nth_Node_From_End_Of_List

019. Remove Nth Node From End Of List

难度: Medium

刷题内容

原题连接

内容描述

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

 给定一个链表: 1->2->3->4->5, 和 n = 2.

 当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

转化为数组,通过数组下标来确定删除的节点
代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} n
* @return {ListNode}
*/
var removeNthFromEnd = function(head, n) {
if (!head || n === 0) {
return head;
}
const list = [];
let cur = head;
while (cur) {
list.push(cur);
cur = cur.next;
}
const index = list.length - n;

if (list.length === 1 && n === 1) {
return null;
}

if (index === 0) {
return list[1]
} else {
list[index-1].next = list[index+1];
return list[0];
}
};

思路2
**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

使用快慢指针的方式,先让fast走n步,再让slow开始和fast一起走,当fast走完的时候,就是slow走到了正确的位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var removeNthFromEnd = function(head, n) {
if (!head || n === 0) {
return head;
}
let dummy = new ListNode(-1);
dummy.next = head;
let fast = dummy;
let slow = dummy;
Array.from(({length:n+1})).forEach(() => {
fast = fast.next;
})
while(fast) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
};