title: Implement queue based on linked list in C++: Error: free() invalid pointer: 0x000...400c1c * (Core dumped)
body: <p>I am learning the algorithms  in &lt; Algorithms> in C++, and now I want to implement the Queue based on linked list. Following is my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  template &lt;typename T&gt;
  class Node
  {
      public:
          typedef T data_t;
          typedef Node&lt;T&gt;* NodePtr;
          data_t item;
          NodePtr next;
  };
  // Queue: FIFO
   template &lt;typename T&gt;
  class Queue
  {
      public:
          typedef T data_t;
          Queue();
  
          bool isEmpty()
          {
              return first == nullptr;
          }
          size_t size()
         {
             return N;
         }
  
         void enqueue(data_t d)
         {
              //temp = new Node&lt;data_t&gt;();
              temp = last;
              last = new Node&lt;data_t&gt;();
              last-&gt;item = d;
              last-&gt;next = nullptr;
              if(isEmpty())
                  first = last;
              else
                  temp-&gt;next = last;
  
              N++;
          }
  
          data_t dequeue()
          {
              data_t t = first-&gt;item;
              temp = first;
              first = first-&gt;next;
              temp-&gt;next = nullptr;
              delete temp;
              temp = nullptr;
              N--;
              if(isEmpty())
                  last = nullptr;
  
              return t;
          }
          ~Queue();
      private:
          int N = 0;
          typename Node&lt;data_t&gt;::NodePtr first = nullptr;
          typename Node&lt;data_t&gt;::NodePtr last = nullptr;
          typename Node&lt;data_t&gt;::NodePtr temp = nullptr;
  };
  
   template &lt;typename T&gt;
   Queue&lt;T&gt;::Queue()
  {
      N = 0; 
      first = nullptr;
      last = nullptr;
      temp = nullptr;
  }
  template &lt;typename T&gt;
  Queue&lt;T&gt;::~Queue()
  {
      cout &lt;&lt; "In destructure function ..." &lt;&lt; endl;
      while(!isEmpty())
      {
          temp = first-&gt;next;
          delete first;
          first = temp;
          N--;
      }
  }
  
  int main(int argc, char **argv)
  {
      Queue&lt;int&gt; que;
      que.enqueue(1);
      que.enqueue(2);
      cout &lt;&lt; "queue's size = " &lt;&lt; que.size() &lt;&lt; endl;
      cout &lt;&lt; que.dequeue() &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>It's alright before the "return 0;" in main function, and this error happens when existing main function.</p>
  
  <p>I guess some mistakes exist in my destructor funciton of class Queue. </p>
  
  <p>What's more, I tried to writing "~Node()" in 'class Node' and didn't use the destructor function in 'class Queue', but not work both.</p>
  
  <p>I've searched this error for one day and not find exactly same problem. Thankyou very much ~</p>