题目介绍
给你一个链表,删除链表的倒数第 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.* 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) {// 遍历所有节点依次入栈,出栈的第n个节点就倒数第n个节点,当前栈顶节点就是其前驱节点ListNode *dummy = new ListNode(-1, head);stack<ListNode*> stk;ListNode *cur = dummy;while(cur){stk.push(cur);cur = cur->next;}// 弹出n个节点for(int i = 0; i < n; ++i){stk.pop();}ListNode *pre = stk.top();pre->next = pre->next->next;ListNode *res = dummy->next;delete dummy;return res;}ListNode* removeNthFromEnd1(ListNode* head, int n) {// 双指针(快慢)ListNode *dummy = new ListNode(-1, head);ListNode *fast = head, *slow = dummy;// 快指针提前走n步for(int i = 0; i < n; ++i) fast = fast->next;// 快指针 和慢指针以及 pre指针一起走while(fast != nullptr){slow = slow->next;fast = fast->next;} // 出循环时, slow到达待删除元素前面的位置// 删除节点slow->next = slow->next->next;ListNode *res = dummy->next;delete dummy;return res;}
};