#include <iostream>
using namespace std;
template<class T>class Stack
{
private:
struct Node
{
T data;
Node *next;
};
Node *head;
Node *p;
int length;
public:
Stack()
{
head = NULL;
length = 0;
}
void push(T n)//入栈
{
Node *q = new Node;
q->data = n;
if (head == NULL)
{
q->next = head;
head = q;
p = q;
}
else
{
q->next = p;
p = q;
}
length++;
}
T pop()//出栈并且将出栈的元素返回
{
if (length <= 0)
{
abort();
}
Node *q;
int data;
q = p;
data = p->data;
p = p->next;
delete(q);
length--;
return data;
}
int size()//返回元素个数
{
return length;
}
T top()//返回栈顶元素
{
return p->data;
}
bool isEmpty()//判断栈是不是空的
{
if (length == 0)
{
return true;
}
else
{
return false;
}
}
void clear()//清空栈中的所有元素
{
while (length > 0)
{
pop();
}
}
};
int main()
{
Stack<char> s;
s.push('a');
s.push('b');
s.push('c');
while (!s.isEmpty())
{
cout << s.pop() << endl;
}
system("pause");
return 0;
}
数据结构--链式栈--C++实现
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:<a>标签
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】C语言实现顺序栈
【数据结构】第三章——栈、队列和数组详细介绍通过C语言实现顺序栈
数据结构 C语言 顺序栈 -
【数据结构】C语言实现共享栈
【数据结构】第三章——栈、队列与数组详细介绍通过C语言实现共享栈
数据结构 C语言 栈 共享栈 -
(C语言)栈的链式实现(数据结构九)
1.数据类型定义在代码中为了清楚的表示一些错误和函数运行状态,我们预先定义一些变量来表示这些状态。在head.h头文件
c 数据结构 栈 单链表 #define -
【数据结构】栈(C++ )
栈栈顺序存储结构实现栈链接存储结构实现栈实际应用迷宫求解表达式求值栈只能在一
数据结构 c++ 栈 数组 入栈 -
数据结构 栈 c++ 源代码实现
数据结构栈的c++源代码实现
数据结构 栈 c/c++ -
【Java数据结构】3.2链式栈
更多IT交流加群:257073626(期待您的加入)
java数据结构 java实现链式栈 java实现栈 java栈实现 java链式栈 -
数据结构 线性表 链式 c++源代码 实现
数据结构 线性表 链式 c++ 源代码实现
数据结构 线性表 链式 c++ 源代码