码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-05 00:34:18      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:efi   tno   The   tco   end   let   node   节点   leetcode   

技术分享图片
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个节点

标签:efi   tno   The   tco   end   let   node   节点   leetcode   

原文地址:https://www.cnblogs.com/yiluyisha/p/9266088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!