Remove Nth Node From End of List

时间:2022-05-11
本文章向大家介绍Remove Nth Node From End of List,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题:删除距离末尾n个距离的结点 分析:先找出距离末尾n个距离的结点其距离开始的距离多少,然后再删除

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int front;
    int dfs(ListNode *head,int n,int step)
    {
        if(head==NULL) return 0;
        int h=dfs(head->next,n,step+1)+1; 
        if(h==n) { front=step;}
        return h;
    }
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(head==NULL) return head;
        front=0;
        dfs(head,n,1);
        ListNode *help = new ListNode(0);
        help->next=head;
        int t=1;
        ListNode *ret=help;
        while(1)
        {
            if(t==front) 
            {
                ret->next=head->next;
                delete head;
                break;
            }
            ret=ret->next;
            head=head->next;
            t++;
        }
        return help->next;
    }
};