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

时间:2020-06-19 00:11:04   收藏:0   阅读:65

题目描述

leetcode - 19:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
技术分享图片

解题关键

碎碎念

中等题因为要求是 一次 循环。所以用两个TreeNode节点tmp和ntmp,ntmp = tmp - n 。简单来说就是tmp往前移动n以后ntmp才开始移动。

代码

/**
 * 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) {
        ListNode* tmp = new ListNode(0);
        ListNode* ntmp = new ListNode(0);
        tmp->next = head;
        ntmp->next = head;
        int flag=0;
        while(tmp!=NULL){
            tmp=tmp->next;
            if(flag>n){
                ntmp=ntmp->next;
            }
            flag++;
        }
        if(ntmp->next==head){
            return head=head->next;
        }
        ntmp->next = ntmp->next->next;
        return head;
    }
};

原文:https://www.cnblogs.com/baboon/p/13160758.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!