Appearance
0019-删除链表的倒数第N个结点
https://leetcode.cn/problems/remove-nth-node-from-end-of-list
给你一个链表,删除链表的倒数第n个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5] 示例 2:
输入:head = [1], n = 1 输出:[] 示例 3:
输入:head = [1,2], n = 1 输出:[1]
提示:
链表中结点的数目为 sz 1 <= sz <= 30 0 <= Node.val <= 100 1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
暴力法
先扫描整个链表的个数,再计算需要删除的节点,然后再删除
csharp
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
int count = 0;
ListNode cur = head;
while(cur != null){
count++;
cur = cur.next;
}
//计算倒数第几个
int index = count - n;
if(index < 0){
return head;
}
cur = dummyHead;
for(int i=0; i<index; i++){
cur = cur.next;
}
cur.next = cur.next.next;
return dummyHead.next;
}
}
双指针法
使用快慢指针,将快指针先走 n 步,然后慢指针出发,指向的下一个节点就是需要删除的节点 注意指针的边界处理
csharp
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode slow = dummyHead;
ListNode fast = dummyHead;
for(int i=0; i<n; i++){
fast = fast.next;
if(fast == null){
return head;
}
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyHead.next;
}
}
AlgoPress