题目链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
给你一个链表,删除链表的倒数第 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
两趟扫描
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre=new ListNode();
ListNode curr=null;
pre.next=head;
curr=pre;
//倒数第n个节点即正数第num-n+1个节点
int num=0;
while(curr.next!=null){
num++;//记录链表节点总个数
curr=curr.next;
}
int N=num-n+1;//正数第N个节点
curr=pre;
int c=N-1;//循环次数
while(c!=0){
curr=curr.next;
c--;
}
curr.next=curr.next.next;
return pre.next;
}
}
进阶:你能尝试使用一趟扫描实现吗?
一趟扫描(双指针)
如果要删除倒数第n个节点,让fast先移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dumyhead=new ListNode();
dumyhead.next=head;
ListNode fast=dumyhead;
ListNode low=dumyhead;
//fast比low先走n步
while(n!=0){
fast=fast.next;
n--;
}
while(fast.next!=null){
fast=fast.next;
low=low.next;
}
low.next=low.next.next;
return dumyhead.next;
}
}