栈的定义
栈是只能在一端插入和删除元素的线性表。
特性:后进先出
栈的术语
入栈(压栈):指将元素压入栈内。
出栈(弹栈):指将元素弹出栈。
栈顶:栈的顶部。
栈底:栈的底部。
栈的基本运算
(1)初始化 :设置栈为空。
(2)判断栈为空:
若为空,则返回TRUE,否则返回FALSE.
(3)判断栈为满:
若为满,则返回TRUE,否则返回FALSE.
(4)取栈顶元素:取出栈顶元素。
条件:栈不空。
否则,应能明确给出标识,以便程序的处理。
(5)入栈:将元素入栈,即放到栈顶。
这里要注意栈满的情况。
(6)出栈:删除当前栈顶的元素。
这里要考虑栈空的情况
栈的实现
这里要注意栈的两种存储结构(线性存储和链式存储)
1.线性存储
源码:
#include<iostream>
using namespace std;
#define maxlen 100 //这里用来定义栈的最大容量
enum error_code {success,overflow,underflow};//用来表示栈功能的实现情况
template<typename T>
class Stack
{
private:
int count; //用来记录栈中元素的数量
T data[maxlen]; //保存栈的元素
public:
Stack(); //构造函数
bool empty() const; //判空
bool full() const; //判满
error_code get_top(T &x) const; //取栈顶的元素
error_code push(const T x); //入栈
error_code pop(); //出栈
};
template<typename T>
Stack<T>::Stack()
{
count = 0;
}
template<typename T>
bool Stack<T>::full() const
{
return count == maxlen-1;
}
template<typename T>
bool Stack<T>::empty() const
{
return count == 0;
}
template<typename T>
error_code Stack<T>::get_top(T &x) const
{
if(empty()) //若栈空则返回underflow(下溢)
return underflow;
x = data[count-1];
return success;
}
template<typename T>
error_code Stack<T>::push(const T x)
{
if(full())//若栈满则返回overflow(溢出)
return overflow;
data[count] = x;
count++;
return success;
}
template<typename T>
error_code Stack<T>::pop()
{
if(empty())//若栈空则返回underflow(下溢)
return underflow;
count--;
return success;
}
int main()
{
return 0;
}
2.链式存储
这里要特别注意把栈顶放在链首还是链尾
为了减少入栈和出栈的时间,把栈顶放在链首
源码:
#include <iostream>
using namespace std;
enum error_code{success,underflow,overflow}; //用来表示栈功能的实现情况
struct node //链的节点
{
int data;
node *next;
};
class Stack
{
private:
node *top; //用来记录栈顶(链首)
int count;
public:
Stack();
~Stack();
bool full() const;
bool empty() const;
error_code get_top(int &x) const;
error_code push(int x);
error_code pop();
};
Stack::Stack()
{
count = 0;
top = NULL;
}
bool Stack::empty() const
{
return count == 0;
}
bool Stack::full() const
{
return false; //因为是链式存储,每次插入仅仅需要申请新的节点即可,因此没有上限
}
error_code Stack::get_top(int &x) const
{
if(empty())
return underflow;
x = top->data;
return success;
}
error_code Stack::push(int x)
{
node* s = new node;
s->data = x;
s->next = top;
top = s;
count++;
return success;
}
error_code Stack::pop()
{
if(empty())
return underflow;
node *s = top;
top = top->next;
delete s;
count--;
return success;
}
Stack::~Stack()
{
while(!empty())
pop(); //只要栈不空就持续出栈
}
int main()
{
return 0;
}
标准模板库里的栈(STL)
1.头文件
2.定义方法:
stack<elementtype>+栈名
如,我要定义一个int型的栈 栈名 mystack
stack<int> mystack;
3.基本运算
push(elementtype x) 将x加入栈中,即入栈操作
pop() 出栈操作(删除栈顶),只是出栈,没有返回值
top() 返回第一个元素(栈顶元素)
size() 返回栈中的元素个数
empty() 当栈为空时,返回 true
stack<int> mystack;
mystack.push(1);
mystack.top();
mystack.size();
mtstack.empty();
mystack.pop();
结语
近期要进行数据结构的期末考,因此便总结了一下课堂上所学到的内容。可能会有很多的错误,感谢大家的指正,谢谢。