C++有栈和队列的函数
#include <queue>
#include <stack>queue < int > Q; //定义int类型为例
stack < int > S;
Stack(堆栈) 是一个容器类的改编,提供了堆栈的全部功能,——也就是说实现了一个先进后出(FILO)的数据结构。
| 操作 | 比较和分配堆栈 |
|---|---|
| empty() | 堆栈为空则返回真 |
| pop() | 移除栈顶元素 |
| push() | 在栈顶增加元素 |
| size() | 返回栈中元素数目 |
| top() | 返回栈顶元素 |
队列是一种容器适配器,一种先进先出(FIFO)的数据结构。
| back() | 返回最后一个元素 |
|---|---|
| empty() | 如果队列空则返回真 |
| front() | 返回第一个元素 |
| pop() | 删除第一个元素 |
| push() | 在末尾加入一个元素 |
| size() | 返回队列中元素的个数 |
C语言的模拟栈与队列操作:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //bool类型需要的头文件
#define ERROR 0
typedef int Position;
typedef int ElementType;
/*栈操作*/
struct SNode
{
ElementType *Data; /* 存储元素的数组 */
Position Top; /* 栈顶指针 */
int MaxSize; /* 堆栈最大容量 */
};
typedef struct SNode *Stack;
Stack CreateStack( int MaxSize )
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
bool IsFull( Stack S )
{
return (S->Top == S->MaxSize-1);
}
bool Push( Stack S, ElementType X )
{
if ( IsFull(S) )
{
printf("堆栈满");
return false;
}
else
{
S->Data[++(S->Top)] = X;
return true;
}
}
bool IsEmpty( Stack S )
{
return (S->Top == -1);
}
ElementType Pop( Stack S )
{
if ( IsEmpty(S) )
{
printf("堆栈空");
return ERROR; /* ERROR是ElementType的特殊值,标志错误 */
}
else
return ( S->Data[(S->Top)--] );
}
/*队列操作*/
struct QNode
{
ElementType *Data; /* 存储元素的数组 */
Position Front, Rear; /* 队列的头、尾指针 */
int MaxSize; /* 队列最大容量 */
};
typedef struct QNode *Queue;
Queue CreateQueue( int MaxSize )
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
bool IsQFull( Queue Q )
{
return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}
bool AddQ( Queue Q, ElementType X )
{
if ( IsQFull(Q) )
{
printf("队列满");
return false;
}
else
{
Q->Rear = (Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear] = X;
return true;
}
}
bool IsQEmpty( Queue Q )
{
return (Q->Front == Q->Rear);
}
ElementType DeleteQ( Queue Q )
{
if ( IsQEmpty(Q) )
{
printf("队列空");
return ERROR;
}
else
{
Q->Front =(Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
int main()
{
printf("Hello world!\n");
return 0;
}