Leetcode Remove Nth Node from End of List

Source: Internet
Author: User

Remove Nth Node from End of List

O (n) complexity

1. Create a new head node as the virtual head so that there are no special cases to consider during the deletion process (the first node is deleted)
2. With two pointers p and Q, when P has gone N-step, in the same time to let PQ go backwards, when p goes to the end is null, Q points to the number of the last nth, the process of recording Father node, directly modify the pointer can be
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 *p, *q,*Pre; -ListNode * node =NewListNode (0);//Add a virtual head node -Node->next =head; thePre =node; -p = q =head; -         if(Head==null)returnNULL; -         intI=0; +         //Add a head node here for easy comprehension and easy removal -         //with two pointers p and Q, when P has gone n steps, when the PQ is left at the same time, when P goes to the end null, Q points to the number of reciprocal nth +         //in the process of recording the Father node, directly modify the pointer can A          while(p!=NULL) { at             if(i>=N) { -Pre =Q; -q= q->Next; -             } -i++; -P=p->Next; in         } -Pre->next = q->Next; to          Free(q); +         returnNode->Next; -     } the};

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.