1
使用标准库的栈和队列时,先包含相关的头文件
#include<stack>
#include<queue>
定义栈如下:
stack<int> stk;
定义队列如下:
queue<int> q;
栈提供了如下的操作
-
s.empty() 如果栈为空返回true,否则返回false
-
s.size() 返回栈中元素的个数
-
s.pop() 删除栈顶元素但不返回其值
-
s.top() 返回栈顶的元素,但不删除该元素
-
s.push() 在栈顶压入新元素
队列提供了下面的操作
-
q.empty() 如果队列为空返回true,否则返回false
-
q.size() 返回队列中元素的个数
-
q.pop() 删除队列首元素但不返回其值
-
q.front() 返回队首元素的值,但不删除该元素
-
q.push() 在队尾压入新元素
-
q.back() 返回队列尾元素的值,但不删除该元素
2
栈是限定仅在表头进行插入和删除操作的线性表,有着先进后出的特点(FILO);
现在我来动手实现栈的基本本功能练练手;
定义栈的头文件如下:
-
#ifndef CSTOCK_H_
-
#define CSTOCK_H_
-
-
const int STOCK_SIZE = 100;
-
typedef int elemType;
-
-
class CStock
-
{
-
public:
-
CStock();
-
-
bool push(elemType x);
-
bool pop(elemType &x);
-
void clear();
-
bool isEmpty();
-
bool isFull();
-
void print();
-
-
~CStock();
-
-
private:
-
elemType elem[STOCK_SIZE];
-
int top;
-
};
-
-
#endif
实现基本功能如下:java
-
#include "Stock.h"
-
#include<iostream>
-
using std::cout;
-
using std::endl;
-
-
-
CStock::CStock():top(-1)
-
{
-
-
}
-
-
-
bool CStock::push(elemType x)
-
{
-
if(top == STOCK_SIZE - 1)
-
{
-
return false;
-
}
-
elem[++top] = x;
-
return true;
-
}
-
-
-
bool CStock::pop(elemType &x)
-
{
-
if(top == -1)
-
{
-
return false;
-
}
-
x = elem[top--];
-
return true;
-
}
-
-
-
void CStock::clear()
-
{
-
top = -1;
-
}
-
-
-
bool CStock::isEmpty()
-
{
-
return top == -1;
-
}
-
-
-
bool CStock::isFull()
-
{
-
return top == STOCK_SIZE - 1;
-
}
-
-
-
void CStock::print()
-
{
-
for(int i = 0; i <= top; i++)
-
{
-
cout << elem[i] << "\t";
-
-
if( (i+1) % 5 == 0)
-
cout << endl;
-
}
-
}
-
-
CStock::~CStock(void)
-
{
-
-
}
栈 基本操作
原文:http://blog.csdn.net/skp127/article/details/51329159