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.

 

Analyse: 如果链表为空,返回NULL;如果n等于链表的长度,即删除head;否则,先找到该删除位置的前一位置,将该位置的next指向被删除位置的next,并释放被删除指针的空间。第一次没有WA或TE就AC了,mark一下~~ :)

 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 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         ListNode *current = head;
13         int length = 0;
14         while(current){
15             length++;
16             current = current->next;
17         }
18         
19         if(length == 1) return NULL;
20         if(length == n){
21             ListNode *temp = head;
22             head = head->next;
23             delete temp;
24             return head;
25         }
26         
27         current = head;
28         for(int i = 1; i < length - n; i++) current = current->next;
29         
30         ListNode *temp = current->next;
31         current->next = current->next->next;
32         delete temp;
33         
34         return head;
35     }
36 };

 

posted @ 2015-04-12 17:05  amazingzoe  阅读(117)  评论(0编辑  收藏  举报