1 loop solution


  • 0
    F

    /**

    • Definition for 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(n==0) return head;

       auto curr = head;
       vector<ListNode*> ln;
       
       while(curr){
           ln.push_back(curr);
           curr = curr->next;
       }
       curr = head;
       if(n == ln.size()){
           head = head->next;
           curr = 0;
           return head;
           
       }
       auto del = ln[ln.size()-n];
       auto next = del->next;
       //since n is always valid
       if(ln.size() <= 1){
           head = 0;
       }
       
       if(ln.size() > 1){
           int preIndex = ln.size()-n-1;
           if(preIndex < 0) preIndex = ln.size()-n;
           auto pre = ln[preIndex];
           pre->next = next;
       }
       del = 0;
       return head;
      

      }
      };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.