Leetcode_19_remove Nth Node from the End of List (easy)

Source: Internet
Author: User

Remove Nth Node from End of List

Topic:

Given A linked list, remove the nth node from the end of the list and return its head.

For example,

   1->2->3->4->5  N = 2.   1->2->3->5.

Note:
Given n would always be valid.
Try to do the in one pass.

Disintegration:
Should loop again, but don't know how much data the list totals

Simple two cycles, but how to predict the future >_<

(Hint: English translation error, Ah, my English is taught by the PE teacher)


#include <iostream>
using namespace Std;

struct ListNode {
int Val;
ListNode *next;
ListNode (int x): Val (x), Next (NULL) {}
};

Class Solution {
Public
listnode* Removenthfromend (listnode* head, int n) {
ListNode *now = head;
int i = 0;
for (; Now!=null;now = Now->next) {
i++;
}
if (n>i) {
return NULL;
}
if (n==i) {
Return head->next;
}
int j = 0;
for (Now=head;now!=null;now = Now->next) {
j + +;
if (j = = I-n) {
ListNode *next = now->next->next;
Delete now->next;
Now->next = Next;
Break
}
}
return head;
}
};

void Printlist (ListNode *head) {
ListNode *now = head;
for (; Now!=null;now = Now->next) {
cout<<now->val<< "and";
}
}

int main (int argc, const char * argv[]) {
ListNode *head = (ListNode *) malloc (sizeof (ListNode));
Head->val = 1;
Head->next = NULL;
ListNode *now = head;
for (int i=2;i<6;i++) {
ListNode *next = (ListNode *) malloc (sizeof (ListNode));
Next->val = i;
Next->next = NULL;
Now->next = Next;
now = next;
}
cout<< "Before" <<endl;
Printlist (head);
cout<<endl;
Solution A;
ListNode *final = A.removenthfromend (head, 2);
cout<< "after" <<endl;
Printlist (final);
return 0;
}
What, altogether over, what

Leetcode_19_remove Nth Node from the End of List (easy)

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.