栈的简单实现——顺序栈

规则:

先进后出 FILO(First In Last Out)

操作:
入栈:push()
出战:pop()
判空:isempty()
判满:isfull()

利用数组,实现顺序栈

入栈:

int push(int num){  //入栈 
	
	stack[++top] = num;
}

出栈:

int pop(){  //出栈 

	return stack[top--]; 
}

判空:

int isempty(int stack[]){  //判空   空,返回 1;不空,返回 0 
	if(top == 0){
		return 1;
	} 
	return 0;
} 

判满:

int isfull(int stack[]){  //判断栈是否满   满,返回 1;不满,返回 0 
	if(top >= MAX-1){
		return 1;
	}
	return 0;
}

示例:

#include<stdio.h>

#define MAX 100

int stack[MAX], top = 0; 

int push(int num){  //入栈 
	
	stack[++top] = num;
}

int pop(){  //出栈 

	return stack[top--]; 
}

int isfull(int stack[]){  //判断栈是否满   满,返回 1;不满,返回 0 
	if(top >= MAX){
		return 1;
	}
	return 0;
}

int isempty(int stack[]){  //判空   空,返回 1;不空,返回 0 
	if(top == 0){
		return 1;
	} 
	return 0;
} 
 
int main(){
	int i;
	
	stack[MAX]={0};  // 1起点数组,stack[0]不存数据 
	
	push(10);  // 10 入栈
	push(11);  // 11 入栈 
	push(12);  // 12 入栈
	
	if(isfull(stack)){           //判满 
		printf("stack is full");
	} 
	else{
		printf("stack: "); 
		for(i=1; i<=top; i++){  //不满则输出栈内元素 
			printf("%d ", stack[i]);
		}
	}
	
	printf("\n");
		
	printf("%d\n", pop());  //出栈 
	printf("%d\n", pop());  //出栈
	
	if(isempty(stack)){           //判空 
		printf("stack is empty");
	} 
	else{
		printf("stack: ");
		for(i=1; i<=top; i++){  //不空则输出栈内元素 
			printf("%d ", stack[i]);
		}
	} 
	 
	return 0;
} 

结果:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章