Remove Nth Node From End of List

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

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

C++:
01 /**
02  * Definition for singly-linked list.
03  * struct ListNode {
04  *     int val;
05  *     ListNode *next;
06  *     ListNode(int x) : val(x), next(NULL) {}
07  * };
08  */
09 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         vector<ListNode*> A;
15         for(ListNode* p=head;p!=NULL;p=p->next)
16         {
17             A.push_back(p);
18         }
19         A.push_back(NULL);
20         int k=A.size();
21         if(k==n+1)
22         {
23             return A[1];
24         }
25         A[kn2]->next=A[kn];
26         return A[0];
27     }
28 };
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s