简易栈模版(链表实现)

本文介绍了一个使用链表实现的栈的模板类,包括基本的栈操作如入栈、出栈、返回栈顶元素等,并提供了一个简单的测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个用链表写的栈的模版,只写了几个最常用的功能,对象的比较没写,就是重载运算符而已。


文件“mystack.h”

#include<iostream> using namespace std; template<class T> class My_stack; template<class T> class Node //结点类 { private: T data; Node<T> *next; public: Node() { next=NULL; } Node(T d) { data=d; next=NULL; } friend My_stack<T>; }; template<class T> class My_stack { private: Node<T> *head; public: My_stack() { head=new Node<T>(); } ~My_stack() { clean(); delete head; } bool empty() const { return (head->next==0); } int size() const { int length=0; Node<T> *p=head->next; while(p) { length++; p=p->next; } return length; } void push(T d) //入栈 { Node<T> *p=new Node<T>(d); p->next=head->next; head->next=p; } T top() //返回栈顶元素 { if(empty()) { cout<<"stack is empty."<<endl; exit(1); } Node<T> *p=head->next; T temp=p->data; return temp; } void pop() //弹出栈顶元素 { Node<T> *p=head->next; head->next=p->next; delete p; } void clean() //清除整个栈 { Node<T> *p=head->next; while(p) { head->next=p->next; delete p; head->next=p; } cout<<"清理完成"<<endl; } };
下面是一个测试代码

main.cpp

#include"mystack.h" #include<string> using namespace std; int main() { My_stack<string> s; if(s.empty()) cout<<"stack is empty"<<endl; //cout<<s.top()<<endl; s.push("dan"); s.push("liu"); s.push("ai"); s.push("wo"); cout<<"Now the stack's size is: "<<s.size()<<endl; while(!s.empty()) { cout<<s.top()<<" "; s.pop(); } cout<<endl; return 0; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值