3.3 Type in a sequence of integers, and push or pop the typed value into the stack by judging

Topic: Suppose a sequence of integers is input from the keyboard: a1, a2, a3,..., an, try to write an algorithm implementation: use a stack structure to store the input integers, when ai≠-1, push ai into the stack; when ai=- At 1, the top integer of the stack is output and popped from the stack. The algorithm should give corresponding information for abnormal situations (stack full, etc.).

Analysis: There are many operations of stacking and popping, and the question mentions the exception "stacking full", so choose the sequential stack.

Idea: Initialize the stack, type a sequence of integers cyclically, and determine whether the entered value is -1. If it is not -1, judge whether the stack is full, if it is full, output "stack full" and exit, otherwise the number will be pushed into the stack; if it is -1, judge whether the stack is empty, if it is empty, output "stack empty" and exit, otherwise output The top element of the stack is popped from the stack.

Algorithm Description:

#difine MAXSIZE 100
typedef int ElemType;  //因为此题中说明了序列中都是整数,用ElemType表示int,便于修改
typedef struct{
    
       //定义栈的结构
	ElemType *base;  
	ElemType *top;  
	int stacksize;
}SqStack;
Status InitStack(SqStack &S){
    
       //初始化栈函数
	S.base=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
	if(!S.base)
		return ERROR;
	S.top=S.base;
	S.stacksize=MAXSIZE;
	return OK;
}
Status InOutS(SqStack &S){
    
    
	ElemType e;
	int n;
	InitStack(S);    //调用初始化函数,对栈进行初始化操作
	for(int i=0;i<n;i++){
    
     
		scanf("%d",&e);	 //循环键入整数,并将键入的数值赋值给变量e;
		if(e!=-1){
    
       //键入的数不是-1
			if(S.top-S.base==S.stacksize){
    
       //栈满
				printf("栈满!");    
				return ERROR;
			}
			*S.top++=e;  //栈未满,将e的值插到栈顶,栈顶指针上移
		}else{
    
       //键入的数为-1
			if(S.top==S.base){
    
      //栈空
				printf("栈空!");
				return ERROR;
			}
			printf("%d",*--S.top);  //输出栈顶元素并出栈
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_39688282/article/details/108104643