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;
    }*/
};

猜你喜欢

转载自www.cnblogs.com/yiluyisha/p/9266088.html