C语言实现的栈和队列需要我们自己手动去实现,以前写过类似的博文,这里就不再重复。博客链接如下:
栈的C语言实现:https://blog.csdn.net/morixinguan/article/details/50507124
队列的C语言实现:https://blog.csdn.net/morixinguan/article/details/51374296
但C++已经提供了相关的类给我们进行操作,我们只需要按照栈和队列的方式来操作数据即可,如下,是栈的使用,非常简单,例如:
#include <iostream>
#include <String>
#include <stack>
using namespace std ;
int main(void)
{
int num = 0 ;
int count = 0 ;
//整型数据入栈出栈操作,定义栈的空间为10
const stack<int>::size_type Stack_Size = 10 ;
//创建一个空栈
stack<int> Stack ;
if(Stack.empty() == true)
cout << "栈为空!" << endl ;
while(Stack.size() != Stack_Size)
{
//入栈===num就是入栈的数据
cout << "入栈:" << num << endl ;
Stack.push(num++);
}
if((Stack.empty() == false)&& (Stack.size() == Stack_Size))
cout << "栈已经满了!" << endl ;
for(int i = 0 ; i < Stack_Size ; i++)
{
//将栈顶的数据打印出来
cout <<"出栈:" << " " << Stack.top() << endl ;
Stack.pop();
}
cout << "====================================================================" << endl ;
//字符串类型的数据入栈出栈操作
const stack<string>::size_type Str_Stack_Size = 4 ;
string array[Str_Stack_Size] = {"Hello world!","Hello Debug!","Hello JIM!","Hello AMY"};
stack<string> Str_Stack ;
if(Str_Stack.empty() == true)
cout << "栈为空!" << endl ;
for(int count = 0 ; count < Str_Stack_Size ; count++)
{
cout << "入栈:" << array[count] << endl ;
Str_Stack.push(array[count]);
}
if((Str_Stack.empty() == false) && (Str_Stack.size() == Str_Stack_Size))
cout << "栈已经满了!" << endl ;
for(int count = 0 ; count < Str_Stack_Size ; count++)
{
cout <<"出栈:" << " " << Str_Stack.top() << endl ;
Str_Stack.pop();
}
return 0 ;
}
运行结果:
再来看看队列的使用,也是类似的,区别只是,队列时先进先出,而栈是先进后出,如下所示:
#include <iostream>
#include <queue>
using namespace std ;
int main(void)
{
const queue<int>::size_type QUEUE_Size = 10 ;
queue<int> Queue;
for(int i = 0 ; i < QUEUE_Size; i++)
{
//入队操作
Queue.push(i);
}
for(int i = 0 ; i < QUEUE_Size ; i++)
{
//把队列数据打出来
cout << Queue.front() << endl ;
//出队
Queue.pop();
}
cout << "====================================================================" << endl ;
const queue<string>::size_type QUEUE_Str_Size = 4 ;
queue<string> Str_Queue ;
string str_array[QUEUE_Str_Size] = {"Hello world!","Hello Debug!","Hello JIM!","Hello AMY"};
for(int i = 0 ; i < QUEUE_Str_Size ; i++)
{
Str_Queue.push(str_array[i]);
}
for(int i = 0 ; i < QUEUE_Str_Size ; i++)
{
cout << Str_Queue.front() << endl ;
Str_Queue.pop();
}
return 0 ;
}
运行结果: