Leetcode|双指针/快慢指针|19. 删除链表的倒数第 N 个结点

2021-09-22 10:56:25 浏览数 (1)

1 快慢指针

代码语言:javascript复制
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        auto pre = new ListNode();
        auto prehead = pre;
        pre->next = head;
        auto slow = head;
        auto fast = head;
        for (int i = 0; i < n; i  ) 
            fast = fast->next;
        while (fast) {
            slow = slow->next;
            pre = pre->next;
            fast = fast->next;
        }
        pre->next = slow->next;
        return prehead->next;
    }
};

0 人点赞