回覆列表
  • 1 # YAO大神

    這是我用連結串列結構實現的棧,以下是演算法,順序表部分沒寫,最近沒什麼時間,不好意思啦。。

    #include<stdio.h>

    #include<stdlib.h> //包括malloc()和realloc()函式的標頭檔案

    #include<math.h> //包括pow()函式的標頭檔案

    #define Max_stack_size 20

    #define Addersize 10

    typedef char Elemtype;

    typedef struct{

    Elemtype *base;

    Elemtype *top;

    int stacksize;

    }sqStack;

    void initStack (sqStack *s){ //初始化一個空棧

    s->base=(Elemtype *)malloc(Max_stack_size*sizeof(Elemtype));

    if(!s->base) exit(0);

    s->top=s->base;

    s->stacksize=Max_stack_size;

    }

    void pushStack(sqStack *s,Elemtype e){ //入棧操作

    if(s->top-s->base>=s->stacksize)

    {s->base=(Elemtype *)realloc(s->base,(s->stacksize+Addersize)*sizeof(Elemtype));

    if(!s->base) exit(0);

    s->top=s->base+s->stacksize;

    s->stacksize=s->stacksize+Addersize;}

    *(s->top)=e;

    s->top++;

    }

    void popStack(sqStack *s,Elemtype *e){ //出棧操作

    if(s->top==s->base) return;

    *e=*--(s->top);

    }

    void clearStack(sqStack *s) //清空棧

    {

    s->top=s->base;

    }

    void destroyStack(sqStack *s){ //銷燬棧

    int i;

    int len;

    len=s->stacksize;

    for(i=0;i<len;i++)

    {free(s->base);

    s->base++;

    }

    s->base=NULL;

    s->top=s->base;

    s->stacksize=0;

    }

    int counterStack(sqStack s)

    {return (s.top-s.base);}

    void main()

    { sqStack p;

    Elemtype c;

    int i,sum,length;

    sum=0;

    printf("initial:\n");

    initStack(&p);

    printf("push the 8 scale:\n");

    scanf("%c",&c); //輸入資料時不能隔開,否則答案錯誤,空格也算字元

    while(c!="#")

    {pushStack(&p,c);

    scanf("%c",&c);

    }getchar();

    length=counterStack(p); //有錯時更容易檢測到。。

    printf("numbers"length:%d\n",length);

    for(i=0;i<length;i++)

    {popStack(&p,&c);

    {sum=sum+(c-48)*pow(8,i);} //二進位制pow(8,i)改為pow(2,i),十六進位制用if else如/**/中所示

    }

    /* if("0"<c<"9") {sum=sum+(c-48)*pow(16,i);}

    else if("A"<c<"Z") {sum=sum+(c-55)*pow(16,i);}

    else if("a"<c<"z") {sum=sum+(c-87)*pow(16,i);}*/

    printf("the answer is:%d\n",sum);

    }

  • 中秋節和大豐收的關聯?
  • 如何看待班級紀律的作文300字?