leetcode题目:remove nth node from end of list

Remove Nth Node From End of List:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
ListNode* (ListNode* head, int n) {
ListNode *fast = head, *slow = head;
while(n--)
fast = fast->next;

if(NULL == fast)
return head->next;
fast = fast->next;
while(fast != NULL){
fast = fast->next;
slow = slow->next;
}
//删除结点
slow->next = slow->next->next;
return head;
}
};