[Leetcode] 19-remove Nth Node from End of List

Source: Internet
Author: User

Original title Link: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/


The problem is to remove the last nth node, by keeping 2 pointers, one fast and one slow, the quick pointer going first n, then the slow pointer going at the same time, until the fast pointer becomes null. This changes the value of the slow pointer to next. (Note that the slow pointer is actually a pointer to the cursor in order to change the value of the pointer to the current node). Personally feel this problem actually must be very careful to do, otherwise it is easy to write wrong. Belong to the idea of simple, but need careful and strong heart.


/** * Definition for singly-linked list. * struct ListNode {*     int val; *     ListNode *next; *     listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public:    listnode *removenthfromend (listnode *head, int n) {        listnode* fast = head;        listnode** slowpp = NULL;                int i = 0;        while (FAST) {            fast = fast->next;                        ++i;            if (i = = N) {                slowpp = &head;            } else if (i > N) {                SLOWPP = & ((*SLOWPP)->next);}         }                if (*SLOWPP) {            listnode* next = (*SLOWPP)->next;            listnode* cur = (*SLOWPP);            Delete (cur);            *SLOWPP = next;        }                return head;    };


[Leetcode] 19-remove Nth Node from End of List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.