棧的簡單實現——順序棧

規則:

先進後出 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;
} 

結果:
在這裏插入圖片描述

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