1.题目
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
2.想法
考研曾经考过的c++经典算法,利用双指针,先令一指针往前走n个节点
再两个指针同时前进,每前进一个就将后指针的节点copy到结果链表中,直到前指针遇到链表尾部即停止,此时后指针所指的节点为倒数第n个节点,并且结果链表已经复制下前面链表,再将前指针跳过倒数第n个节点后面部分连接上即为最终结果
3.图解
来源:leetcode官方图解
4.自己解法
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode resulthead=new ListNode(0);
ListNode cur=resulthead;
ListNode p=head;//后指针
ListNode q=head;//前指针
while(n-->0)
{
q=q.next;
}
while(q!=null)
{
cur.next=new ListNode(p.val);
cur=cur.next;
p=p.next;
q=q.next;
}
cur.next=p.next;
cur=cur.next;
return resulthead.next;
}
}
5.知识点
(1)链表的尾插法
引用到leetcode2两数相加java题解中的java链表尾插法
(2)双指针
类似用法:leetcode11盛最多水的容器java题解(双指针)中是关于数组使用双指针
6.官方解法
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-by-l/
来源:力扣(LeetCode)
7.疑惑点
(1)时间空间的击败率少不清楚,虽然用官方题解去试,击败率也是一样,可能还有更好的解决办法