首页 > 学院 > 开发设计 > 正文

栈 — 顺序栈

2019-11-10 17:18:39
字体:
来源:转载
供稿:网友

代码

/* function:sequence stack created by : xilong date: 2017.2.9*/#include "iostream"#include <stdlib.h>#include <math.h>using namespace std;#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0#define STACK_SIZE 20#define STACK_INCREMENT 10typedef int Status;typedef int Elemtype;typedef struct{ Elemtype *base; Elemtype *top; int stackSize;} sqStack;/* initialize the stack*/void Init_Stack(sqStack *s){ s->base = (Elemtype *)malloc(STACK_SIZE *sizeof(Elemtype)); if (!s->base) { exit(0); } s->top = s->base; s->stackSize = STACK_SIZE;}/* push*/void Push_Stack(sqStack *s, Elemtype e){ if (s->top - s->base >= s->stackSize) { s->base = (Elemtype *)realloc(s->base, (s->stackSize + STACK_INCREMENT) * sizeof(Elemtype)); if (!s->base) { exit(0); } s->top = s->base + s->stackSize; s->stackSize = s->stackSize + STACK_INCREMENT; } *(s->top) = e; s->top++;}/* Pop*/void Pop_Stack(sqStack *s, Elemtype *e){ if (s->top == s->base) { exit(0); } *e = *--(s->top);}/* destory the stack*/Status Destory_Stack(sqStack *s){ int i; for (i = 0; i < s->stackSize; i++) { free(s->base); s->base++; } s->base = s->top = NULL; s->stackSize = 0; return OK;}/* the length of the stack*/int Length_Stack(sqStack *s){ return(s->top - s->base);}void main(){ sqStack s; Elemtype e; int len, i; Init_Stack(&s); Push_Stack(&s, 1); Push_Stack(&s, 2); Push_Stack(&s, 3); Push_Stack(&s, 4); Push_Stack(&s, 5); Push_Stack(&s, 6); cout << "the length of the stack currently:"; cout << Length_Stack(&s) << endl; len = Length_Stack(&s); cout << "出栈顺序为:"; for (i = 0; i < len; i++) { Pop_Stack(&s, &e); cout << e << " "; } cout << endl; //Destory_Stack(&s); system("pause");}

截图

这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表