循序栈

#include<stdio.h>
#include<stdlib.h>
#define stack_initSize 100
#define stack_incrementSize 10
typedef struct{
 int * stackdata;
 int top;
 int stacksize;
}seqStack;
void InitStack(seqStack *S){//初始化栈

 if(!S)  {printf("顺序栈无效\n"); return;}
  S->stackdata=(int *)malloc(stack_initSize*sizeof(int));
     S->top=0;
  S->stacksize=stack_initSize;
     }


 void InStack(seqStack * S,int e){//进栈
  int * newstack;
  if(!S)  {printf("顺序栈无效\n"); return;}
   if(S->top==S->stacksize){
     newstack=(int*)realloc(S->stackdata,(S->stacksize+stack_incrementSize)*sizeof(int));
     if(!newstack) { printf("内存分配错误\n");return;}
     S->stackdata=newstack;
     S->stacksize=S->stacksize+stack_incrementSize;
   }
   S->stackdata[S->top++]=e;
 }                                                                                                                                                                                                                                                                                                                                          

 void OutStack(seqStack *S){//出栈
    int e;
       if(!S)  {printf("顺序栈无效\n"); return;}
    if(S->top==0) {printf("栈为空\n"); return;}
    e=S->stackdata[--S->top];
    printf("%d",e);
}
   
   
   
 void TraversalStack(seqStack * S){//遍历栈
         int i;
      for(i=0;i<S->top;i++){
     
       printf("%d\t",S->stackdata[i]);
     
      }
      printf("\n");
   
    }
 void LengthStack(seqStack *S){//栈长
  printf("栈的长度为%d\n",S->top);
 
 }
    void IsEmpty(seqStack *S){//判断是否为空
  if(!S)  {printf("顺序栈无效\n"); return;}
     if(S->top==0) printf("栈为空\n");
  else
   printf("栈不为空\n");
}


  int main(void){
   seqStack *S=(seqStack*)malloc(sizeof(seqStack));
   int i,x,z;
   int y=1;
   while(y){
       printf("***********************\n");
    printf("--1.初始化栈--\n");
    printf("--2.进栈--\n");
    printf("--3.出栈--\n");
    printf("--4.遍历栈--\n");
    printf("--5.求栈长--\n");
       printf("--6.栈是否为空--\n");
    printf("--7.进制转换--\n");
    printf("--8.退出--\n");
                printf("--请选择你要进行的操作--\n");
    scanf("%d",&i);
    switch(i){
    
    case 1:InitStack(S);printf("栈已经初始化\n");break;
    case 2: printf("请输入你要进栈的元素\n");scanf("%d",&x);InStack(S,x);printf("%d已经进栈\n",x);break;
    case 3: OutStack(S); printf("\n已经出栈\n");break;
    case 4: TraversalStack(S);break;
    case 5: LengthStack(S);break;
    case 6: IsEmpty(S);break;
    case 7:
     printf("请输入你要转换的10进制数:\n");
         scanf("%d",&z);
      InitStack(S);
      while(z){
      InStack(S,z%2);
      z=z/2;
      }
      printf("转换结果为:\n");
      while(S->top!=0){
      OutStack(S);
      }
      printf("\n");

     break;
    case 8: y=0;printf("已退出\n");break;

   }
   }

  return 0;  

posted @ 2017-11-13 22:25  Saruka的男朋友  阅读(122)  评论(0)    收藏  举报