Linked list stack implementation I have used the following code for a stack implementation. The top keeps track of the topmost node of the stack. Now since top is a data member of the node function, each node created will have a top member, which ideally we wouldn't want.


Is this good approach to coding?
Will making top as static make it a better coding practice?
Should I have a global declaration of top?




#include&lt;iostream&gt;
using namespace std;
class node
{
    int data;
    node *top;
    node *link;
    public:
    node()
    {
       top=NULL;
       link=NULL;
    }
    void push(int x)
    {
        node *n=new node;
        n-&gt;data=x;
        n-&gt;link=top;
        top=n;
        cout&lt;&lt;"Pushed "&lt;&lt;n-&gt;data&lt;&lt;endl;
    }
    void pop()
    {
        node *n=new node;
        n=top;
        top=top-&gt;link;
        n-&gt;link=NULL;
        cout&lt;&lt;"Popped "&lt;&lt;n-&gt;data&lt;&lt;endl;
        delete n;
    }
    void print()
    {
        node *n=new node;
        n=top;
        while(n!=NULL)
        {
            cout&lt;&lt;n-&gt;data&lt;&lt;endl;
            n=n-&gt;link;
        }
        delete n;
    }
};


int main()
{
    node stack;
    stack.push(5);
    stack.push(7);
    stack.push(9);
    stack.pop();
    stack.print();
}


Any other suggestions welcome. I have also seen codes where there are two classes, where the second one has the top member. What about this?
In the pop and the print function, the new node seems unnecessary, since the next line modifies the pointer to point to the top. It could be simply

node *n = top;

The delete n; also looks superfluous in the print since n will always be NULL there.
If I'm right making top as static or global would result that you can't have more than one stack in an application. Linked lists usually have two classes: one is a Node which stores a reference to the next node and the data, and the second is a LinkedList class which stores the head and the implementation of the push, pop, etc. methods. You can see an example in this answer.
Take care of the boundary cases. Calling pop on an empty stack gives a segmentation fault error. I suppose that's not the best error handling method :)