题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
示例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
进阶:你能尝试使用一趟扫描实现吗?
Java解法
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if ((head == null) || n <= 0) return head;
ListNode first = head, second = head;
for (int i = 1; i <= n; ++i) {
if (second == null) return head;
second = second.next;
}
if (second == null) {
first = head;
head = head.next;
// 切断联系;
first.next = null;
first = null;
return head;
}
while (second.next != null) {
first = first.next;
second = second.next;
}
second = first.next;
first.next = second.next;
// 切断联系;
second.next = null;
second = null;
return head;
}
}
C++解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// 基本条件检测
if (!head || n <= 0) return head;
// 推进;
ListNode *pFirst = head, *pSecond = head;
for (int i = 1; i <= n; ++i) {
if (!pSecond) return head;
pSecond = pSecond->next;
}
// 检测;
if (pSecond == nullptr) {
pFirst = head, head = head->next;
delete pFirst;
return head;
}
// 继续推进
while (pSecond->next) {
pFirst = pFirst->next;
pSecond = pSecond->next;
}
pSecond = pFirst->next;
pFirst->next = pSecond->next;
delete pSecond;
return head;
}
};
关于作者
- GoGoDeveloper 毕业于中国科学技术大学, 目前是【抖音业务线软件开发工程师】。
- 学习 C++, 算法刷题交流、优质编程资料共享、大厂内推机会,关注 GoGoDeveloper.
1. 微信公众号
2. 知识星球
- C++学习交流 算法刷题答疑 大厂内推机会 t.zsxq.com/13MC3YkK6