Leetcode:remove Nth Node from End of List

Source: Internet
Author: User

First, the topic

Given a single linked list, delete the last nth node and return the deleted list.

For example: known: 1->2->3->4->5, n = 2.

After processing: 1->2->3->5.

try to iterate through the completion.

Second, analysis

See this question my first feeling is a double pointer, because to delete the number of the last nth, so the spacing of two pointers is this n, when the right hand pointer reaches the end, then the left pointer is the next pointer to delete the node. In fact, there are several special cases:

1, {1,2},n=1;

2, {1,2},n=2;

3. {},0

Of course, one might say that n can be greater than the number of nodes, but this topic has already limited n is valid.

Extensions: 1, n values are not limited

2, linked list is not limited to single-linked list, to remove the bottom of the node from the head of n

/** * 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) {    if (head==null| | Head->next==null) return NULL;        ListNode *rnode = head;    ListNode *lnode = head;            for (int i=1; i<=n; i++) {        Rnode = rnode->next;        }         if (rnode==null) {        head = head->next;        return head;        }        while (rnode->next!=null) {        Lnode = lnode->next;        Rnode = rnode->next;        }    Lnode->next = lnode->next->next;        return head;    };

Leetcode: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.