数据结构链栈

//链栈

template<class T>

struct node

{

node<T>* next;//链表指针域

T date;//数据域

};

template<class T>

class Stack

{

public:

Stack();//初始化栈

~Stack();//析构链栈

void pushstack(T date);//入栈

void print();//遍历栈

T popstack(T* date);//出栈

private:

int count;//记录结点个数

node<T>* phead;//头结点

};

template<class T>

T Stack<T>::popstack(T* date)//出栈

{

if (!phead->next)//无数据就不不给出栈

return 0;

node<T>* newnode = phead;

*date = newnode->next->date;

newnode->next = newnode->next->next;

return *date;

}

template<class T>

void Stack<T>::print()

{

node<T>*p = phead;

cout << "链栈元素为: ";

while (p->next != nullptr)

{

p = p->next;

cout << p->date << " ";

}

cout << endl;

}

template<class T>

void Stack<T>::pushstack(T date)

{

node<T>*cur = new node<T>;

cur->date = date;

cur->next = phead->next;

phead->next = cur;

++count;

}

template<class T>

Stack<T>::Stack()

{

phead = new node<T>;

phead->next = nullptr;

phead->date = 0;

count = 0;

cout << "初始化链栈完毕" << endl;

}

template<class T>

Stack<T>::~Stack()

{

//删除链表

node<T>* newnode = phead;

node<T>* p = nullptr;

while (newnode->next != nullptr)

{

p = newnode;

newnode = newnode->next;

delete p;

}

delete newnode;

newnode = nullptr;

cout << "删除链表成功" << endl;

}

int main()

{

Stack<int>s1;

s1.pushstack(1); s1.pushstack(2); s1.pushstack(3); s1.pushstack(4); s1.pushstack(5);

s1.print();

int i = 0;

s1.popstack(&i);

cout << i << endl;

s1.print();

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值