天天看點

棧的實作--C語言版本

源碼:

#include "stdio.h"
#include "stdlib.h"

#define STACK_SPACE 10
typedef struct Stack_list
{
  int * Stack_Space;//棧空間
  int  Stack_top;   //棧頂
  int  Stack_bottom;//棧底
}*pStack;

void Stack_creat(pStack * S);
void Stack_push(pStack S);
void Stack_out(pStack S);
void Stack_pri(pStack S);
int main(void)
{
	pStack s;
	int dp;
	char ch,bh;
	Stack_creat(&s);
	while(1)
	{
	  Stack_push(s);
	  printf("是否繼續壓入   Y     N\n");
	  scanf("%c",&ch);
	  if(ch=='Y')
	     continue;
	  else
	     break;
	}
	getchar();
	while(1)
	{
	  Stack_out(s);
	  printf("是否繼續彈出   Y     N\n");
	  scanf("%c",&bh);
	  if(bh=='Y')
	     continue;
	  else
	     break;
	}
	 Stack_pri(s);
   return 0;
}
void Stack_creat(pStack * S)
{
	(*S)->Stack_Space=(int *)malloc(STACK_SPACE*sizeof(int));
	if((*S)->Stack_Space==NULL)
	{
	  printf("error malloc\n");
	}
	(*S)->Stack_top=(*S)->Stack_bottom=0;
}
void Stack_push(pStack S)
{
  int num;
  printf("請輸入要入棧的元素\n");
  scanf("%d", &num);
  getchar();
  S->Stack_Space[S->Stack_top]=num;
  if(S->Stack_top==STACK_SPACE)
  {
    printf("棧區已滿了,不可再壓入\n");
    return;
  }
  S->Stack_top++;
}
void Stack_out(pStack S)
{
  int data;
  if(S->Stack_top==S->Stack_bottom)
  {
    printf("stack full\n");
    return;
  }
  else
  {
    data=S->Stack_Space[S->Stack_top-1];
    printf("%d 已出棧\n",data);
    S->Stack_top--;
  }
}

void Stack_pri(pStack S)
{
	while(S->Stack_top!=S->Stack_bottom)
	{
	 printf("%d\n",S->Stack_Space[S->Stack_top-1]);
	 S->Stack_top--;
	}
  
}
           

運作結果:

繼續閱讀