Is this good code? Linked List Stack Implementation

Posted by Quik Tester on Stack Overflow See other posts from Stack Overflow or by Quik Tester
Published on 2012-06-30T15:12:10Z Indexed on 2012/06/30 15:15 UTC
Read the original article Hit count: 399

Filed under:
|
|
|

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.

Firstly, is this good approach to coding?
Secondly, will making top as static make it a better coding practice?
Or should I have a global declaration of top?

#include<iostream>
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->data=x;
        n->link=top;
        top=n;
        cout<<"Pushed "<<n->data<<endl;
    }
    void pop()
    {
        node *n=new node;
        n=top;
        top=top->link;
        n->link=NULL;
        cout<<"Popped "<<n->data<<endl;
        delete n;
    }
    void print()
    {
        node *n=new node;
        n=top;
        while(n!=NULL)
        {
            cout<<n->data<<endl;
            n=n->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?

Thanks. :)

© Stack Overflow or respective owner

Related posts about c++

Related posts about data-structures