c++面相对象之链式栈

一.用链表实现栈

template<class T>
class cStack
{    cNode<T> *front;
     int count;
public:
    cStack()
    {
        front = NULL;
        count = 0;
    }
    ~cStack()
    {
        clear();
    }
    void push(T x)
    {
        cNode<T> *p = new cNode<T>(x);
        p->next = front;
        front = p;
        count++;
    }
    
    void pop()
    {
        cNode<T> *p = front;
        if(p)
        {
            count--;
            front = front->next;
            delete p;
        }
    }
    
    T top()
    {
        return front->data;
    }
    
    bool empty()
    {
        return(!count);
    }
    void clear()
    {
        cNode<T> *p = front;
        while(p)
        {
            cNode<T> *t = p;
            p = p->next;
            delete t;
            
        }
        count = 0;
    }
    
    T size()
    {
        return count;
    }
 
};

1.对于栈来说,其本身只需要关注栈顶,所以只需要一个节点指向栈顶即可

2.同样需要有cNode<T> *p = front;创建新节点,便于实现操作。

二.测试

int main()
{
    cStack<int> st;
 
     for(int i=1; i<=5; i++) st.push(i);
     while(!st.empty())
     {
         cout<<st.top()<<endl;
          st.pop();
     }
     cout<<endl;
     for(int i=1; i<=5; i++) st.push(i);
     while(!st.empty())
     {
        cout<<st.top()<<endl;
          st.pop();
     }
     cout<<endl;
     return 0;
}

测试结果为:

三.关于用链表实现栈、队列等数据结构的看法

1.首先,与数组相比,链表的创建会复杂一些,但其功能实现上却比数组要强大得多,所以,链式存储本身也会给运行空间带来更高效的使用。

2.对于面向对象应用而言,链表会作为更为普遍的方式来实现更多的数据结构。

(以上是暂时的思考,一定有考虑不周之处,有错希望大家直接指出)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值