回覆列表
  • 1 # 使用者6840987323640

    用棧實現了判斷迴文數的操作,即把字串依次入棧,然後出棧並依次和字元陣列比較是否相等,從而判斷字元序列是否迴文數,程式碼如下:

    #include "stdio.h"

    #include "stdlib.h"

    #include "string.h"

    #define EMPTY 0

    #define FULL 10000

    #define MAX 10000

    typedef char data;

    typedef struct elem {

    data d;

    struct elem *next;

    }elem;

    typedef struct stack {

    int cnt;

    elem *top;

    }stack;

    void initialize(stack *stk);

    void push(data d, stack *stk);

    data pop(stack *stk);

    bool empty(const stack *stk);

    bool full(const stack *stk); //棧操作函式

    void initialize(stack *stk)

    {

    stk->cnt = 0;

    stk->top = NULL;

    }

    bool empty(const stack *stk)

    {

    return stk->cnt == EMPTY;

    }

    bool full(const stack *stk)

    {

    return stk->cnt == FULL;

    }

    void push(data d, stack *stk)

    {

    elem *p;

    if (!full(stk))

    {

    p = (elem *)malloc(sizeof(elem));

    p->d = d;

    p->next = stk->top;

    stk->top = p;

    stk->cnt++;

    }

    }

    data pop(stack *stk)

    {

    data d;

    elem *p;

    if(!empty(stk))

    {

    d = stk->top->d;

    p = stk->top;

    stk->top = stk->top->next;

    stk->cnt--;

    free(p);

    }

    return d;

    }

    int main(void)

    {

    data input[MAX];

    stack temp;

    int i = 0;

    int flag = 0;

    initialize(&temp); //初始化臨時棧

    scanf("%s", &input); //輸入字串

    while (input[i] != "@")

    {//字串入棧

    push(input[i], &temp);

    i++;

    }

    while (!empty(&temp))

    {//字元依次出棧和字元陣列比較,判斷是否迴文數

    if (temp.top->d == input[flag])

    {

    pop(&temp);

    flag++;

    }

    else

    {

    printf("此字元序列不是迴文數!\n");

    break;

    }

    }

    if (empty(&temp))

    printf("此字元序列是迴文數!\n");

    return 1;

    }

    執行結果:

  • 中秋節和大豐收的關聯?
  • 成熟的人會怎樣面對愛而不得?