栈队结构C++实现

    顺序栈与队使用数组储存数据:

#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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值