题解 | #删除链表的倒数第n个节点#

删除链表的倒数第n个节点

http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param n int整型 
     * @return ListNode类
     */
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // write code here
        if(!head || !n)
            return head;
        if(n == 1 && !head->next)
            return nullptr;
        ListNode* reHead = reverseList(head);
        ListNode* tmpHead = reHead;
        if(n == 1)
        {
            ListNode* tmp = tmpHead->next;
            return reverseList(tmp);
        }

        while(n--)
        {
            if(n == 1)
            {
                ListNode* tmp = tmpHead->next->next;
                tmpHead->next = tmp;
            }
            else
                tmpHead = tmpHead->next;
        }
        return reverseList(reHead);
    }

    ListNode* reverseList(ListNode* head)
    {
        if(!head || !head->next)
            return head;
        ListNode* ret = nullptr;
        while(head)
        {
            ListNode* tmp = head->next;
            head->next = ret;
            ret = head;
            head = tmp;
        }
        return ret;
    }

};
全部评论
也不算新思路吧,反转链表
点赞 回复 分享
发布于 2021-09-15 11:13

相关推荐

牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务