LeetCode:删除链表的倒数第N个节点

Posted 一路一沙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:删除链表的倒数第N个节点相关的知识,希望对你有一定的参考价值。


C++示例:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    // 一趟扫描实现
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == NULL) {
            cout << "The list is empty." << endl;
            return head;
        }
        if (head->next == NULL) {
            delete head;
            return NULL;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }
        if (fast == NULL) {
            ListNode* temp = head->next;
            head->val = temp->val;
            head->next = temp->next;
            delete temp;
            return head;
        }
        while (fast->next != NULL) {
            fast = fast->next;
            slow = slow->next;
        }
        ListNode* temp = slow->next;
        slow->next = temp->next;
        delete temp;
        return head;
    }
    
    // 两趟扫描实现
    /*ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == NULL) {
            cout << "The list is empty." << endl;
            return NULL;
        }
        if (head->next == NULL) {
            delete head;
            return NULL;
        }
        ListNode* p = head;
        int len = 0;
        while (p != NULL) {
            len++;
            p = p->next;
        }
        p = head;
        int pos = len - n + 1;
        while (pos > 2) {
            pos--;
            p = p->next;
        }
        if (pos == 1) {
            ListNode* temp = head->next;
            head->val = temp->val;
            head->next = temp->next;
            delete temp;
            return head;
        }
        ListNode* temp = p->next;
        p->next = temp->next;
        delete temp;
        return head;
    }*/
};

以上是关于LeetCode:删除链表的倒数第N个节点的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 19删除链表的倒数第N个节点

Leetcode 19 删除链表的倒数第 N 个节点

LeetCode 第18题 删除链表的倒数第N个节点

LeetCode - 19 - 删除链表的倒数第N个节点 - Java

LeetCode(19):删除链表的倒数第N个节点

LeetCode 19 - 删除链表的倒数第N个节点 - [链表]