本週學了棧,棧是一種比較基礎的數據結構。特點是先進後出,想象自己做公交車,你先上了車走到了公交車的最後面,車上站滿了人,要下車的時候,後來上車的人卻能先下車。


    棧在很多問題上有用處,比如計算字符串的值等等。


    接下來使用c語言實現的幾個棧的功能。



首先是 數據結構

typedef int ElemType;
typedef struct{
	ElemType elem[MAXSIZE];
	int top;
}SqStack;

初始化

void InitStack(SqStack *p){
	p->top=0;
}


棧添加元素

void Push(SqStack *p,ElemType	x){
	if(p->top<MAXSIZE-1){
		p->top++;p->elem[p->top]=x;
	}
	else 
		printf("\n    Overflow");	
}

棧釋放元素

ElemType Pop(SqStack *p){
	ElemType x;
	if(p->top!=0){
		x=p->elem[p->top];
		p->top--;
		return x;
	}
	else{
		printf("\n     Underflow");
		return -1;
	}		
}

獲得棧頂元素

ElemType GetTop(SqStack	p){
	ElemType x;
	if(p.top!=0){
		x=p.elem[p.top];
		return x;
	}
	else{
		printf("\n     Underflow");
		return -1;
	}
}

輸出棧內元素

void OutStack(SqStack	p){
	int i,j;
	if(p.top==0)
		printf("\n    The Stack is NULL.");
	for(i=p.top;i>0;i--)
		printf("\n  %2d  %6d",i,p.elem[i]);
		
	
}

最後是 主函數

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct{
	ElemType elem[MAXSIZE];
	int top;
}SqStack;
void OutStack(SqStack p);
void InitStack(SqStack *p);
void Push(SqStack *p,ElemType x);
ElemType Pop(SqStack *p);
ElemType GetTop(SqStack p);
int main(int argc, char *argv[])
{
	SqStack q;
	int i;
	int y;
	int cord;
	ElemType a;
	do{
		printf("\n");
		printf("\n		主菜單");
		printf("\n	1 初始化順序棧		\n");
		printf("\n	2 插入一個元素		\n");
		printf("\n	3 刪除棧頂元素		\n");
		printf("\n	4 取出棧頂元素		\n");
		printf("\n	5 結束程序運行		\n");
		printf("\n----------------------\n");
		printf("輸入你的選擇(1,2,3,4,5)");
		scanf("%d",&cord);
		switch(cord)
		{
			case 1:{
				InitStack(&q);
				OutStack(q);
			}break;
			case 2:{
				printf("\n	請輸入要插入的數據 a=");
				scanf("%d",&a);
				Push(&q,a);
				OutStack(q);
			}break;
			case 3:{
				a=Pop(&q);
				printf("\n a=%d",a);
				OutStack(q);
			}break;
			case 4:{
				y=GetTop(q);
				printf("\n y=%d",y);
				OutStack(q);
			}break;
			case 5:exit(0);
		}
		
	}while(cord<=5);
	return 0;
}

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