remove-nth-node-from-end.cpp (1087B)
1 #include <iostream> 2 using namespace std; 3 4 5 //Time: 3ms Beats: 83.17% 6 //Memory: 10.7MB Beats: 39.89% 7 8 struct ListNode { 9 int val; 10 ListNode *next; 11 }; 12 13 14 15 16 ListNode* removeNthFromEnd(ListNode* head, int n) { 17 ListNode* itr1 = head; 18 ListNode* itr2 = head; 19 int length = 0; 20 while(itr1 != NULL){ 21 itr1 = itr1->next; 22 length += 1; 23 } 24 n = length - n; 25 if(n == 0){ 26 return head->next; 27 } 28 int count = 0; 29 while (count < n - 1){ 30 itr2 = itr2->next; 31 count += 1; 32 } 33 ListNode* itr3 = itr2->next; 34 itr2->next = itr3->next; 35 return head; 36 } 37 38 39 int main(){ 40 41 ListNode* ln1 = new ListNode; 42 ListNode* ln2 = new ListNode; 43 ListNode* ln3 = new ListNode; 44 ListNode* ln4 = new ListNode; 45 ln1->val = 10; 46 ln2->val = 4; 47 ln3->val = 5; 48 ln4->val = 9; 49 ln1->next = ln2; 50 ln2->next = ln3; 51 ln3->next = ln4; 52 53 54 ListNode* itr = removeNthFromEnd(ln1, 2); 55 for(int i = 0 ; i < 3; ++i){ 56 cout << itr->val << " "; 57 itr = itr->next; 58 } 59 cout << endl; 60 return 0; 61 }