leetcode力扣刷题打卡
题目:19. 删除链表的倒数第 N 个结点
描述:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
解题思路
1、可以用数组存储链表节点;
2、用双指针,见代码;
原代码##
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p = head;
ListNode *slow = head;
ListNode *fast = head;
for (int i = 0; i < n; ++i) {
fast = fast->next;
}
if (!fast) return slow->next;
while (fast->next) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return p;
}
};