Remove Nth Node from End of List

Source: Internet
Author: User

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removenthfromend (listnode* head,intN) {if(head==null&&head->next==NULL)returnNULL; ListNode* Newhead= (listnode*)malloc(sizeof(ListNode)); Newhead->next=Head; ListNode* pre=Newhead; ListNode* behind=Newhead; N++;  for(intI=0; i<n-1; i++) Pre=pre->Next;  while(pre->next) {Pre=pre->Next; Behind=behind->Next; } behind->next=behind->next->Next; returnNewhead->Next; }};

The problem is to delete the last nth node, so find the bottom n+1 node first and then delete it. Since it is possible to delete the first node of a linked list, you need to insert an empty head node at the beginning of the list.

Before you write a question, think of several special cases ahead of time:

1. Null is returned when the head pointer is empty or if the list has only one node

2. The node to be deleted is the head node or the tail node

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.