LeetCode19. 删除链表的倒数第 N 个结点
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
代码
/*** 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) {ListNode* dummyhead = new ListNode(0);dummyhead->next = head;ListNode* fast = dummyhead;ListNode* slow = dummyhead;while(n--) fast = fast->next;while(fast->next){slow = slow->next;fast = fast->next;}slow->next = slow->next->next;return dummyhead->next;}
};