【Leetcode】19.删除链表的倒数第N个节点(击败100%)

在这里插入图片描述

在这里插入图片描述

/*
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
*/
#include "iostream"

using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    void print(ListNode *head)
    {
        ListNode *p = head;
        while (p != NULL)
        {
            cout << p->val << " ";
            p = p->next;
        }
        cout << endl;
    }
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        ListNode *s = head;
        int num = 1;

        if (n == 1)
        {
            if (s->next == NULL)
                return NULL;
            while (s->next->next != NULL)
            {
                num++;
                s = s->next;
            }
            s->next = NULL;
            return head;
        }

        while (s->next != NULL)
        {
            num++;
            s = s->next;
        }
        s = head;

        if (num == n)
            return head->next;

        while (num - n - 1)
        {
            num--;
            s = s->next;
        }
        // cout << s->val;
        s->next = s->next->next;
        return head;
    }
};

int main(int argc, char const *argv[])
{
    int N, x;
    ListNode *p, *head;

    cout << "input N:";
    cin >> N;

    cout << "input x:";
    cin >> x;
    p = new ListNode(x);

    head = p;

    for (int i = 1; i < N; i++)
    {
        cin >> x;
        p->next = new ListNode(x);
        p = p->next;
    }

    Solution so;
    int n;
    cout << "input n:";
    cin >> n;
    so.print(head);
    so.removeNthFromEnd(head, n);
    so.print(head);

    return 0;
}
发布了73 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104077914