C语言实现栈的操作

更新时间:2023-11-16 12:19:01 阅读量: 教育文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

# define ERROR 0

# define OVERFLOW -2

# define STACK_INIT_SIZE 100 # define STACKINCREMENT 10 #include #include #include #include typedef struct {

int *base; int *top; int stacksize; }SqStack; SqStack S;

int menu_select() {

char c;

do{system(\printf(\

printf(\栈的操作***********\\n\printf(\〓 ☆| 1.建立一个栈☆ 〓\\n\printf(\〓 ☆| 2.元素进栈 ☆ 〓\\n\printf(\〓 ☆| 3.元素出栈 ☆ 〓\\n\printf(\〓 ☆| 0.退出 ☆ 〓\\n\printf(\printf(\ Give your Choice(0-3):\c=getchar();

}while(c<'0'||c>'3'); return(c-'0'); }

void StackDisplay(SqStack &S) {

if(S.top==S.base) printf(\栈为空\int *p;

for(p=S.top-1;p>=S.base;--p) {

printf(\|-|\printf(\}

- 1 -

int InitStack(SqStack &S) { if(S.base!=NULL) {

printf(\栈已建立,请勿重复建立\\n\printf(\system(\return 0; }

else if(S.top==S.base) {

printf(\栈为空,建立一个栈------\printf(\

S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int)); if(!S.base) exit(OVERFLOW); S.top=S.base;

S.stacksize=STACK_INIT_SIZE; int i=1; char sign;

while(sign!='n'&&sign!='N') {

printf(\

printf(\输入入栈的第%d数据:\scanf(\StackDisplay(S);

printf(\scanf(\i++; } } }

void Push(SqStack &S) {

char sign; int e;

if(S.top-S.base>=S.stacksize) {

S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int)); if(!S.base) exit(OVERFLOW); S.top=S.base+S.stacksize;

S.stacksize+=STACKINCREMENT; }

- 2 -

printf(\进栈前栈中元素为↓↓↓\\n\StackDisplay(S);

while(sign!='n'&&sign!='N') {

printf(\接收进栈元素\scanf(\*S.top++=e;

printf(\进栈后栈中元素为↓↓↓\\n\StackDisplay(S);

printf(\scanf(\} }

void Pop(SqStack &S) {

char sign; int e;

while(sign!='n'&&sign!='N') {

if(S.top==S.base) {

printf(\栈是空栈,无法操作!\\n\break; }

printf(\出栈前栈中元素为↓↓↓\\n\StackDisplay(S); e=*--S.top;

printf(\出栈的元素为 e=%d\printf(\

printf(\出栈后栈中元素为↓↓↓\\n\StackDisplay(S);

printf(\scanf(\} }

void main() {

for(;;) {

switch(menu_select())

- 3 -

{

case 1: printf(\ printf(\建立一个栈-------------\\n\ printf(\ InitStack(S); break; case 2: printf(\ printf(\元素进栈-------------\\n\ printf(\ Push(S);

system(\ break; case 3: printf(\ printf(\元素出栈----------\\n\ printf(\ Pop(S);

system(\ break; case 0: printf(\ printf(\ printf(\

system(\ exit(ERROR); } } }

- 4 -

1.选择功能1建立一个建立栈,采用循环接收元素建栈

2.元素进栈,采用循环语句,循环接收元素

3.元素循环出栈,栈中为空时,不能出栈,无法操作,跳出此功能

- 5 -

*刚开始不建立栈,直接选择功能3,栈为空,不能出栈

*刚开始不建立栈,直接选择功能2,栈为空,直接进栈

0.退出操作

- 6 -

本文来源:https://www.bwwdw.com/article/b9dv.html

Top