本篇总结数据结构中有关栈和队列的题目中所用到的栈和队列的知识。
主要包括C++中栈和队列的一些常见的函数和使用方法,栈和队列作为参数传递时的方法,以及自行实现栈和队列的方法。
1. 栈的创建和常用方法
(1)栈的创建
包括头文件<stack>,以及作为参数传递时接受方为stack<Elemtype>stk。
#include <iostream>
#include<stack>
using namespace std;
void Init_Stack(stack<char>stk)
{
while(!stk.empty())
stk.pop();
}
int main()
{
stack<char>stk;
//对栈进行初始化
Init_Stack(stk);
return 0;
}
(2)栈的常用方法
stack<char>stk;//创建一个栈
stk.push('a');//向栈内压入一个成员
stk.pop();//从栈顶弹出一个成员
falg=stk.empty();//如果栈为空返回true
Top=stk.top();//返回栈顶元素,但不删除
num=stk.size();//返回栈内元素个数
2. 队列的创建和常用方法
(1)队列的创建
#include <iostream>
#include<queue>
using namespace std;
void Init_Queue(queue<char>q)
{
while(!q.empty())
q.pop();
}
int main()
{
queue<char>q;//创建一个队列
Init_Queue(q);
return 0;
}
(2)队列的常用方法
queue<char>q;//创建一个队列
q.push('a');//向队尾压入一个成员
q.pop();//从队头出一个成员
falg=q.empty();//如果队列为空返回true
frot=q.front();//返回队首元素
tail=q.back();//返回队尾元素
num=q.size();//返回队列内元素个数
3. 自行实现栈
实现栈比较简单,参考下面实现队列即可。列出一些不同点:
(1)栈只有栈顶成员top,初值应该赋为-1;
(2)入栈时先top++,然后压入元素;
4. 自行实现队列
需要注意两个点:
(1)注意队首和队尾的初值,front=0,rear=-1;
(2)入队列的时候先改变队尾元素指针,再将值入队列;
(3)push和pop时都是先+1再%Maxlen;
(4)求队尾元素上一个时,(rear-1+Maxlen)%Maxlen;
#include <iostream>
#include<stdio.h>
#include<malloc.h>
using namespace std;
typedef struct{
int *data;
int MaxLen;//队列最大长度
int rear;//队尾
int frot;//队头
int length;//当前队列长度
}Queue;
void Create_Queue(Queue *que,int n)
{
que->data=(int *)malloc(sizeof(int)*n);
que->MaxLen=n;
que->length=0;
que->frot=0;//注意,队首初值为0,队尾初值为-1
que->rear=-1;
}
void Qpush(Queue *que,int tmp)
{
que->rear=(que->rear+1)%que->MaxLen;//先改变队尾节点,在赋值元素
que->data[que->rear]=tmp;
que->length++;
}
void Qpop(Queue *que)
{
que->frot=(que->frot+1)%que->MaxLen;
que->length--;
}
int Qfront(Queue *que)
{
return que->data[que->frot];
}
int Qback(Queue *que)
{
return que->data[que->rear];
}
int Qempty(Queue *que)
{
if(que->length==0)
return 1;
else
return 0;
}
int Qsize(Queue *que)
{
return que->length;
}
int main()
{
int n;
cin>>n;
Queue *que;
que=(Queue *)malloc(sizeof(Queue));
Create_Queue(que,n);
free(que);
return 0;
}