顺序栈与队使用数组储存数据:
#include <iostream>
#define MAX 10
using namespace std;
//循环链表测试
void queue(){
//定义一个循环队列,并初始化
int queue[MAX];
int front = 0;
int rear = 0;
//入队enter queue,最多同时储存MAX-1个元素,必须有一个空间被浪费
for(int i = 0; i < 9; i++) {
//判断是否满队
if ((rear+1)%MAX != front) {
//从尾部插入,实现循环
rear = (rear+1) % MAX;
queue[rear] = i;
cout << i << endl;
} else {
cerr << "queue overflow" << endl;
}
}
//出队depart queue
cout << "-" << endl;
int out;
while(front != rear){
//从头部取出,实现循环
front = (front+1) % MAX;
out = queue[front];
cout << out << endl;
}
}
//顺序栈测试
void stack(){
//定义并初始化一个栈
int stack[MAX];
int top = -1;
//入栈
for (int i = 0; i < 10; i++) {
if (top != MAX - 1) {
stack[++top] = i;
cout << i << endl;
} else {
cerr << "stack overflow" << endl;
}
}
cout << "-" << endl;
//出栈
int out;
while (top != -1) {
out = stack[top--];
cout << out << endl;
}
}
int main(int argc, char** argv) {
stack();
}
链栈与队都是线表结构:
#include <iostream>
#include <stdlib.h>
using namespace std;
//节点,队和栈使用相同的节点
typedef struct Node {
int data;
struct Node *next;
} Node;
//队头结点
typedef struct Queue {
struct Node *front;
struct Node *rear;
} Queue;
//栈头结点
typedef struct Stack {
struct Node *top;
} Stack;
void queue(){
//定义队,并初始化
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->front = NULL;
queue->rear = NULL;
//进队enter queue,由于队空与队满的判断条件不能一样,所以一定有一个空间是浪费掉的
for (int i = 0; i < 10; i++){
//定义队并初始化
Node *node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
cout << i << endl;
//判断是否队满
if (queue->front == NULL || queue->rear == NULL) {
queue->front = queue->rear = node;
} else {
queue->rear->next = node;
queue->rear = node;
}
}
cout << "-" << endl;
//出队depart queue
int out;
while (queue->front != NULL && queue->rear != NULL) {
Node *node = queue->front;
out = node->data;
cout << out << endl;
queue->front = node->next;
free(node);
}
}
void stack(){
//定义栈并初始化
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->top = NULL;
//压栈(push stack)
for (int i = 0; i < 10; i++){
Node *node = (Node*)malloc(sizeof(Node));
node->data = i;
cout << i << endl;
node->next = stack->top;
stack->top = node;
}
cout << "-" << endl;
//弹栈(pop stack)
int out;
while (stack->top != NULL) {
Node *node = stack->top;
out = node->data;
cout << out << endl;
stack->top = node->next;
free(node);
}
}
int main(){
stack();
}