1. 程式人生 > >順序棧的C語言實現——初始化函式、入棧函式和出棧函式

順序棧的C語言實現——初始化函式、入棧函式和出棧函式

將順序棧的結構定義為:

#define  M  100   //棧的空間

typedef struct

  {   int data[M];

int top;

  } SqStack;

試寫出SqStack的初始化函式、入棧函式和出棧函式 。並在main()函式中測試上述函式。

#include <stdio.h>
#include <stdlib.h>
#define M 100
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0


typedef struct{
	int data[M];
	int top;
} SqStack;


void SqStackInit(SqStack *S){
	S->top = -1;
}

int SqStackPush(SqStack *S,int x){
	if (S->top == M - 1){
		return FALSE;
	}
	S->top++;
	S->data[S->top] = x;
	return TRUE;
}


int SqStackPop(SqStack *S, int *x){
	if (S->top == - 1){
		return FALSE;
	} else {
		*x = S->data[S->top];
		S->top--;
		return TRUE;
	}
}

int main() {
	SqStack S;
	int i;
	int n;
	SqStackInit(&S);        
	printf("請輸入棧元素:\n");
	int x;
	while(scanf("%d",&x)!=EOF){
		SqStackPush(&S,x);  
	}
	printf("輸出棧元素:\n");
	for (i = 0; i < M; ++i)	{
		if(SqStackPop(&S,&n))           
            printf("%d ",n);
	}
	printf("\n");
	return 0;
}