0
点赞
收藏
分享

微信扫一扫

【LC】删除链表的倒数第N个节点

肉肉七七 2022-03-22 阅读 65

题目描述[简单]:在这里插入图片描述

题解:
求得链表长度,得出正向遍历的次数,使用快慢指针,删除对应结点

/**
 * 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:
    int getlen(ListNode* head)
    {
        int count = 0;
        while(head != NULL)
        {
            ++count;
            head = head->next;
        }
        return count;
    }
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(n <= 0) return nullptr;
        ListNode* fast = head;
        ListNode* slow = NULL;
        int forward = getlen(head) - n;
        if(forward == 0) return head->next;
        while(forward--)
        {
            slow = fast;
            fast = fast->next;
        }
        slow->next = fast->next;
        return head;
    }
};
举报

相关推荐

0 条评论