一、题目

二、两种解题思路
①方法一:二次遍历法
1)方法介绍:
时间复杂度:O(2n)
空间复杂度:O(n)
2)核心代码:
public static ListNode removeNthFromEnd(ListNode head, int n) {
int count = 0;
ListNode cur = new ListNode(0);
cur.next = head;
ListNode first = head;
while ( first!= null) {
count++;
first = first.next;
}
count -= n;
first=cur;
while (count > 0) {
count--;
first = first.next;
}
first.next = first.next.next;
return cur.next;
}
②方法二:快慢n步指针
1)方法介绍:
时间复杂度:O(n)
空间复杂度:O(n)
2)核心代码:
public static ListNode removeNthFromEnd1(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
三、LeetCode成功截图

四、感想
加油,加油,再加油,坚持,坚持,再坚持。
本文详细解析了LeetCode中删除链表倒数第N个节点的问题,提供了两种解题思路:二次遍历法和快慢n步指针法。二次遍历法时间复杂度为O(2n),空间复杂度为O(n);快慢n步指针法时间复杂度为O(n),空间复杂度为O(n)。文章通过具体代码实现了这两种方法,并分享了LeetCode的成功截图。
263

被折叠的 条评论
为什么被折叠?



