π Problem Details
πWhat Were My Initial Thoughts?
- we will require two interations
- 1 to determine size of list
- 2nd to iterate to nth last position and remove the element
π€What Did I Struggle With?
- dummy and temp node usage to correctly remove the node and have the previous node point to the correct next node
π‘ Explanation of Solution
same as intuition
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
π» Implementation of 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) {
ListNode* temp = head;
int size = 0;
while(temp != nullptr){
temp = temp->next;
size++;
}
if(size - n == 0){
head = head->next;
return head;
}
ListNode* pre = head;
temp=head;
for(int i=0; i<size-n; i++){
pre=temp;
temp = temp->next;
}
pre->next=temp->next;
return head;
}
};