Tuesday, February 22, 2022

LeetCode 19. Remove Nth Node From End of List

Problem: - https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
auto fast = head;
auto slow = head;
// fast: move n step
while(n){
fast = fast->next;
n--;
}
// if reaches the tail, remove head
if(!fast){
head = head->next;
return head;
}
// move fast to tail
while(fast->next){
fast = fast->next;
slow = slow->next;
}
// remove
slow->next = slow->next->next;
return head;
}
};

No comments:

Post a Comment