title: Questions Regarding : Find the Sum of Last N nodes of the Linked List
body: <p>I was solving this problem, Actually I did finish it. However, I still want to enhance my solution. Like is there another approach to solve this problem so the time complexity is reduced? my solution's time complextiy is O(n^2). Furthermore, I thought about a way to solve it recursively, but at the end I mixed the both; as I will traverse &quot;Iteratively&quot; to get <code>numOfNodes</code> and then traverse &quot;Recursively&quot; to count the last nodes. I did not implement it yet but I am confused about that solution and I do not know if it is right or not!</p>
  <p>**please have a look at the code first ,,,,,,,,,,,,,,,,,,,,,
  The idea about it is to count to <code>numOfNodes</code> in the list, and then come over and traverse again but for each node I will reduce the <code>numOfNodes</code>. and when <code>numOfNodes == k</code>, then the sum is being calculated using a for loop.</p>
  <p>Here is the code:</p>
  <pre><code>public int sum(Node head, int k){
        int sum = 0;
        int numOfNodes = 0;
  
  
        Node temp = new Node(0);
        temp = head;
        
  
        while(temp != null){
            numOfNodes++;
            temp = temp.next;
        }
        
        temp = head;
        
        while(temp != null){
            if(numOfNodes == k){
              for(int i = 0; i&lt;k; i++){
                  sum += temp.data;
                  temp = temp.next;
              }
            }else{
              numOfNodes--;
              temp = temp.next;
            }
        }
        
        return sum;
      }
  </code></pre>
  <p>Thank you in advance!</p>