您的位置:首页 > Web前端 > Node.js

leetcode Remove Nth Node from Linked List

2015-03-21 01:30 204 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == NULL){
return NULL;
}
ListNode* fast = head, *slow = head;
for(int i = 0; i < n; ++i){
fast = fast->next;
}
//if we want to delete the first node of linked list
if(fast == NULL){
ListNode* tmp = slow->next;
delete slow;
return tmp;
}
while(fast->next != NULL){
slow = slow->next;
fast = fast->next;
}

ListNode* tmp = slow->next->next;
ListNode* tode = slow->next;
slow->next = tmp;
delete tode;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: