b2c网站可分为国际军事新闻
19. 删除链表的倒数第 N 个结点https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
1、题目
给你一个链表,删除链表的倒数第 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
进阶:你能尝试使用一趟扫描实现吗?
2、题解
题解1:不使用头结点
/*** 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 cur = head;int size = 0;// 计算链表的长度while(cur != null) {size++;cur = cur.next;}int index = size - n;// 如果删除的是头节点,直接返回 head.nextif(index == 0) {return head.next;}cur = head;// 遍历到删除节点的前一个节点for(int i = 0; i < index - 1; i++) {cur = cur.next;}// 删除节点if(cur != null && cur.next != null) {cur.next = cur.next.next;}return head;}
}
题解2:使用头结点
/*** 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 dummyHead = new ListNode(0);dummyHead.next = head;// cur 用于遍历链表ListNode cur = dummyHead;int size = 0;// 计算链表的长度while(cur != null) {size++;cur = cur.next;}// 计算要删除节点的索引int index = size - n;// 重新将 cur 指向虚拟头节点,准备遍历到删除节点的前一个节点cur = dummyHead;// 遍历到删除节点的前一个节点for(int i = 0; i < index - 1; i++) {cur = cur.next;}// 删除节点,跳过要删除的节点cur.next = cur.next.next;// 返回修改后的链表,跳过虚拟头节点return dummyHead.next;}
}
题解3:使用头结点+快慢指针法
/*** 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 dummyNode = new ListNode(0);dummyNode.next = head;// 初始化快慢指针,均指向虚拟头节点ListNode fast = dummyNode;ListNode slow = dummyNode;// 快指针先移动 n+1 步,以便保持快慢指针之间的距离为 n+1n++;while(n > 0 && fast != null) {fast = fast.next; // 快指针向前移动n--; // 移动步数减少}// 快指针到达链表末尾时,慢指针正好指向待删除节点的前一个节点while(fast != null) {fast = fast.next; // 快指针继续向前移动slow = slow.next; // 慢指针也向前移动}// 删除目标节点,慢指针的下一个节点就是要删除的节点slow.next = slow.next.next;// 返回去除虚拟头节点后的链表return dummyNode.next;}
}