Remove Nth Node From End of List Runtime Error -


given linked list: 1->2->3->4->5, , n = 2.

after removing second node end, linked list becomes 1->2->3->5. hi, run code in computer leetcode says runtime error. doing wrong in memory? ran same case leetcode said wrong. believe checked corner cases. input [1,2] output [2]

/**  * definition 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) return head;         listnode* tmp =head;         int size =1;         while(tmp->next){           tmp=tmp->next;           size++;         }          if(n>size) return head;         listnode* prev = head;         //delete head         if (n==size){             if(prev->next){             prev=prev->next;             delete head;             head = prev;             return head;             } else {                 delete head;                 return null;                  }         }else {         (int j=0; j<size-n-1; j++) {             prev = prev->next;         }         tmp=prev->next;         //if tail, delete, else reconnect.         if (tmp->next){         prev->next = tmp->next;         }         delete tmp;         return head;     }     } }; 


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -