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)