注:本程序由Visual Studio 2015编写,与VC++6.0稍有区别,复制到VC++6.0注释掉“#include “stdafx.h””即可运行,复制到VS可直接运行。
#include "stdafx.h"#include <stdio.h>#include <iostream>using namespace std;#define OK 1#define ERROR 0#define OVERFLOW -1#define UNDERFLOW -2#define STACK_INIT_SIZE 80#define STACKINCREMENT 10typedef int status;#define ElemType chartypedef struct {ElemType *base;ElemType *top;int stacksize;}SqStack;SqStack S;#define MAXQSIZE 80typedef struct {ElemType *base;int front;int rear;}SqQueue;SqQueue Q;status InitStack(SqStack &S) //初始化栈{S.base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));if (!S.base)exit(OVERFLOW);S.top = S.base;S.stacksize = STACK_INIT_SIZE;return OK;}status InitQueue(SqQueue &Q) { //初始化队列Q.base = (ElemType*)malloc(MAXQSIZE * sizeof(ElemType));if (!Q.base)exit(OVERFLOW);Q.front = Q.rear = 0;return OK;}status Push(SqStack &S, ElemType e) {//入栈if (S.top-S.base == S.stacksize) {S.base = (ElemType*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType));if (!S.base)exit(OVERFLOW);S.top = S.base + S.stacksize;S.stacksize += STACKINCREMENT;}*S.top++ = e;return OK;}status EnQueue(SqQueue &Q, ElemType e) { //入队if ((Q.rear + 1) % MAXQSIZE == Q.front)return ERROR;//队满Q.ar] = ar = (Q.rear + 1) % MAXQSIZE;return OK;}status Pop(SqStack &S, ElemType &e) {//出栈if (S.top == S.base)exit(UNDERFLOW);e = *(S.topp-1);return OK;}status DeQueue(SqQueue &Q, ElemType &e) { //出队if (Q.front == Q.rear)return ERROR; //队空e = Q.base[Q.front];Q.front = (Q.front + 1) % MAXQSIZE;return OK;}status StackEmpty(SqStack S) {//是否为空栈return S.base == S.top;}status QueueEmpty(SqQueue Q) {//是否为空队ar == Q.front;}void algo(SqQueue &Q) {//栈实现队的首尾逆置ElemType e;InitStack(S);cout << " 栈逆置队列前元素如下:";while (!QueueEmpty(Q)) {DeQueue(Q, e);cout << e;Push(S, e);}cout << endl;while (!StackEmpty(S)) {Pop(S, e);EnQueue(Q, e);}}int main() {InitQueue(Q);ElemType e;int num;cout << "tttt*ttttt*";cout << endl << "tttt*t计科1512-02210151232-杨少通t*" << endl;cout << "tttt*****************************************" << endl << endl;cout << "****************栈逆置队列元素****************" << endl << endl;cout << " 请输入初始化队列元素个数:";cin >> num;for (int i = 0; i < num; i++) {cout << " 请输入第" << i + 1 << "个元素:";cin >> e;EnQueue(Q, e);}algo(Q);cout << " 栈逆置队列后元素如下:";while (!QueueEmpty(Q)){DeQueue(Q, e);cout << e;}cout << endl << endl;return 0;}
如有转载请注明来源: www.dreamload/blog/?p=251&preview=true (洋葱先生)
本文发布于:2024-02-01 08:51:06,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170674866835413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |