[19] Leetcode delete list penultimate N nodes (the double pointer Method)

Here Insert Picture DescriptionHere Insert Picture Description

/*
给定一个链表,删除链表的倒数第 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)
    {

        if (head->next == NULL)
        {
            return NULL;
        }

        ListNode *p = head, *s = head;

        for (int i = 0; i < n; i++)
        {
            s = s->next;
        }

        if (s == NULL)
        {
            return p->next;
        }

        while (s->next != NULL)
        {
            s = s->next;
            p = p->next;
        }

        p->next = p->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;
}
Published 74 original articles · won praise 128 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44936889/article/details/104078050