class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head == NULL) return head;
//be careful when there is only one node and delete it.
ListNode dummy(-1);
dummy.next = head;
ListNode *slow = &dummy, *fast = &dummy;
while(n--)
{
fast = fast->next;
}
//make sure fast is the last element, not null
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next;
}
ListNode *cur = slow->next;
slow->next = cur->next;
delete cur;
return dummy.next;
}
};
Remove Nth Node From End of List
最新推荐文章于 2021-08-04 10:48:57 发布