数据结构(c++)栈的模板类(使用链表实现)

  1. List Node.h
#ifndef LISTNODE_H
#define LISTNODE_H
#include<iostream>
/*
Create by 软件工程 gpwner  2016年11月28日17:37:23
*/
using namespace std;
template<class Type>
class ListNode
{
public:

    //链表结点构造函数
    ListNode ( ):link(NULL) {}
    ListNode ( const Type& item ):data(item),link(NULL) {}
    ~ListNode()
    {
    }
    Type GetData()
    {

        return  data;
    }
    ListNode<Type> *GetNext()
    {
        return link;

    }
    void SetNext(ListNode<Type> *node)
    {
        link=node;
    }
private:
    Type data;
    ListNode<Type> *link;
};

#endif // LISTNODE_H

  1. Stack.h
#ifndef STACK_H
#define STACK_H
#include<ListNode.h>

/*
Create by 软件工程 gpwner  2016年11月28日17:37:23
*/
template <class Type>
class Stack
{
public:
    //构造函数
    Stack()
    {
        top=NULL;
    }
    //析构函数
    ~Stack()
    {

        while(top!=NULL)
        {
            ListNode<Type> *tempNode=top;
            top=top->GetNext();
            delete tempNode;
        }
    }
    //新元素进栈
    void Push(const &x)
    {
        ListNode<Type>  *newNode=new ListNode<Type>(x);
        if(top==NULL)
        {
            top=newNode;
        }
        else
        {
            newNode->SetNext(top);
            top=newNode;
        }
    }
    //栈顶元素出栈
    Type Pop()
    {
        if(top==NULL)
        {
            return NULL;
        }
        Type data=top->GetData();
        ListNode<Type> *tempNode=top;
        delete tempNode;
        top=top->GetNext();
        return data;
    }
    //判断当前栈是否为空
    bool IsEmpty()
    {
        if(top==NULL)
            //为空的时候返回false
            return false;
        else
            //非空的时候返回true
            return true;
    }
    //获取当前栈有多少个元素
    int Size()
    {
        int num=0;
        ListNode<Type> *current=top;
        while(current!=NULL)
        {
            current=current->GetNext();
            num++;
        }
        return num;
    }
    //获取栈顶元素
    Type Top()
    {
        if(top!=NULL)
            return top->GetData();
        return NULL;
    }
private:
    ListNode<Type> *top;
};

#endif // STACK_H

3.main.cpp

#include <iostream>
#include<Stack.h>
using namespace std;
/*
Create by 软件工程 gpwner  2016年11月28日17:37:23
*/
int main()
{
    Stack<int> *mstack=new Stack<int>();
    for(int i=10; i<20; i++)
        mstack->Push(i);
    mstack->Pop();
    mstack->Push(99);
    cout<<"当前栈中元素个数:"<<mstack->Size()<<endl;
    cout<<"栈顶元素是:"<<mstack->Top()<<endl;

    cout<<"当前栈中的所有的元素(栈顶--->栈底):"<<endl;
    while(mstack->IsEmpty())
    {
        cout<<mstack->Top()<<"  ";
        mstack->Pop();
    }
    cout<<endl;
    //释放内存
    delete mstack;
    return 0;
}

运行结果:这里写图片描述

如果有需要工程源码的请到我的个人Github上去下载

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值