title: Stack Using Linked List in C++
body: <p>I'm trying to create a stack using linked lists in c++. But the display function i have written prints only the top of the stack. I can't really understand why this is happening. Any help or clarification is much appreciated. Thanks</p>
  
  <pre><code>#include&lt;iostream.h&gt;
  #include&lt;conio.h&gt;
  
  class Node
  {
  protected:
  
      Node* next;
      int data;
  
  public:
  
      Node(int d){data=d;}
      friend class Stack;
  };
  
  class Stack
  {
  public:
      Stack(){top-&gt;next='\0';length=0;}
  
  void push(int d)
  {
      Node *n=new Node(top-&gt;data);
      n-&gt;next='\0';
      top-&gt;next=n;
      top-&gt;data=d;
      length++;
  }
  
  int pop()
  {
      top=top-&gt;next;
      length--;
      return top-&gt;data;
  }
  
  void displaystack()
  {
      while(top-&gt;next!='\0')
      {
          cout&lt;&lt;top-&gt;data&lt;&lt;endl;
      top=top-&gt;next;
      }
  }
  
  int getlength()
  {
      return length;
  }
  
  private:
      Node *top;
      int length;
  
  };
  
  void main()
  {
      clrscr();
      Stack s;
      s.push(9);
      s.push(8);
      s.push(7);
      s.push(6);
      s.push(5);
      s.push(3);
      s.displaystack();
      int len=s.getlength();
      cout&lt;&lt;"length of stack is "&lt;&lt;len&lt;&lt;endl;
      getch();
  }
  </code></pre>
  
  <p>It only prints the following:
  3
  the length of stack is 6</p>
  
  <p>--------xxxxxxx-------xxxxxxxx--------xxxxxxx-----------xxxxxxxxxxxxx--------------</p>
  
  <p>After editing the code looks like this: 
  and works too! (thanks to @Kaathe) :P</p>
  
  <pre><code>#include&lt;iostream.h&gt;
  #include&lt;conio.h&gt;
  
  class Node
  {
  protected:
  Node* next;
  int data;
  
  public:
  
  Node(int d){data=d;}
  friend class Stack;
  };
  
  class Stack
  {
  public:
  Stack(){top-&gt;next=NULL;length=0;}
  ~Stack()
  {
       while(top!=NULL)
   {
     Node* toDelete=top;
     top=top-&gt;next;
     delete toDelete;
   }
  
  }
  
  void push(int d)
  {
  Node *n=new Node(d);
  n-&gt;next=top;
  top=n;
  length++;
  }
  
  int pop()
  {
   Node* oldtop=top;
   top=top-&gt;next;
   int oldtopdata=oldtop-&gt;data;
   delete(oldtop);
   --length;
   return oldtopdata;
  }
  
  void displaystack()
  {
  Node* current=top;
  while(current-&gt;next!=NULL)
      {
      cout&lt;&lt;current-&gt;data&lt;&lt;endl;
      current=current-&gt;next;
      }
  }
  
  int getlength()
  {
  return length;
  }
  
  private:
  Node *top;
  int length;
  
  };
  </code></pre>