19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

题解:

        本题主要思路时一直关注倒数第n个,从指针 1 遍历开始就计算 head 是倒数第几个,当 head 是倒数第 n 个时就用指针 2 开始记录第 n 个的位置,指针 1 和 2 同时变化,则指针 2 一直指向倒数第 n 个节点,则当直到指针 1 遍历全部链表,则指针 2 位置为倒数第 n 个。具体细节见代码:

/**
 * 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(n == 0){
            return head;
        }
        ListNode *ptr, *prep; // 指向当前节点
        ListNode *nth, *prepNth; // 指向倒数第n个节点
        int num = 0;
        prep = head, ptr = head->next, num++; //初始化当前指针
        nth = prepNth = NULL;
        if(num == n){
            nth = head; 
            // 针对 n = 1 情况
            // 初始化nth指针,当 num == n 时,说明已经走过 n 个节点,令nth指向head;
        }
        while(ptr != NULL){
            if(nth != NULL){
                // 指针移动
                prepNth = nth;
                nth = nth->next;
            }
            prep = ptr;
            ptr = ptr->next;
            num++;           
            if(num == n){
                nth = head;
                // 针对 n > 1 情况
            }
        }
        if(nth == NULL){
            return head; // 当倒数第 n 个不存在
        }
        else if(nth == head){
            return head->next; // 当倒数第 n 为第一个
        }
        // 其余情况
        prepNth->next = nth->next;
        nth->next = NULL;
        //free(nth);
        return head;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值