Leetcode 19. Remove Nth Node From End of List

99 阅读1分钟

LeetCode链接

比较easy的类似题型试做 [剑指 Offer 22. 链表中倒数第k个节点]

和简单题区别: 这道题不应该去找delete node,而是找delete node前一个node

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head->next == nullptr){
            return nullptr;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        
        int count = n;
        while(count > 0){
            fast = fast->next;
            count --;
        }
        if(fast == nullptr){
            return head->next;
        }
        while(fast->next != nullptr){
            slow = slow->next;
            fast = fast->next;
        }

        slow->next = slow->next->next;

        return head;
    }
};

视频解析: neetcode