• Remove Nth Node From End of List


    Given a linked list, remove the nth node from the end of list and return its head.

    For example,

       Given linked list: 1->2->3->4->5, and n = 2.
    
       After removing the second node from the end, the linked list becomes 1->2->3->5.
    

    Note:
    Given n will always be valid.
    Try to do this in one pass.

    由于删除头结点时要改变头结点的指针,所以传入的是引用或者使用二级指针。提示中给的只是传入一级指针,要是删除头结点,始终不能删掉。(注意要改变一个数据结构时,要传二级指针或者引用,树中的很多操作都是这样的)

    C++实现代码如下:

    #include<iostream>
    #include<new>
    using namespace std;
    
    //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)
                return NULL;
            ListNode *p=head;
            ListNode *q=head;
            ListNode *pre=head;
            int i=0;
            while(q&&i<n)
            {
                q=q->next;
                i++;
            }
            //说明没有n个元素
            if(i<n)
               return head;
            while(q)
            {
                pre=p;
                p=p->next;
                q=q->next;
            }
            if(p==head)
            {
                head=head->next;
                delete p;
            }
            else
            {
                pre->next=p->next;
                delete p;
            }
            return head;
        }
        void createList(ListNode *&head)
        {
            ListNode *p=NULL;
            int i=0;
            int arr[10]= {10,9,8,7,6,5,4,3,2,1};
            for(i=0; i<5; i++)
            {
                if(head==NULL)
                {
                    head=new ListNode(arr[i]);
                    if(head==NULL)
                        return;
                }
                else
                {
                    p=new ListNode(arr[i]);
                    p->next=head;
                    head=p;
                }
            }
        }
    };
    
    int main()
    {
        Solution s;
        ListNode *L=NULL;
        s.createList(L);
        ListNode *head=L;
        while(head)
        {
            cout<<head->val<<" ";
            head=head->next;
        }
        cout<<endl;
        s.removeNthFromEnd(L,5);
        while(L)
        {
            cout<<L->val<<" ";
            L=L->next;
        }
    }

    运行结果:

  • 相关阅读:
    HBase 超详细介绍
    写在之前
    【CF】38E Let's Go Rolling! (dp)
    [CF] E. Camels
    CF9D How many trees? (dp)
    [CF] 8C Looking for Order
    CF dp 题(1500-2000难度)
    NOIP原题板刷
    Codeforces Round #595 (Div. 3) 题解
    CSP-S2019 停课日记
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4098255.html
Copyright © 2020-2023  润新知