Leetcode Remove Nth Node from End of List

Source: Internet
Author: User

This question if according to normal idea, usually is the two sides traverse, the first time is calculates the chain list the length, then determines the reciprocal nth node the positive sequence number, then accesses can.

The better way is to find a pointer p point to the head node after the n+1 nodes, and then at the same time to move the opposite node and p back, if p=null, then the head pointer is exactly pointing to the penultimate n+1 node. Here is a question, if n is exactly equal to the length of the list, it is obvious that the head pointer is pointing at the head node, and there is no precursor to the head node, and that sentence in the code solves the problem, that is, when there is no n+1 judgment, then NULL is the case.

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: OneListNode *removenthfromend (ListNode *head,intN) { AListNode *end =head; -ListNode *f =head; -     inti =0; the      while(End! = null&&i<n+1) -     { -End = End->Next; -i++; +         if (end = = null&&i<n+1)return head = head->Next ;              +     } A      while(End! =NULL) at     { -Head = head->Next; -End = End->Next; -     } -Head->next = head->next->Next; -     returnF; in } -};

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.