C堆疊的程式問題

將數值讀入並推入堆疊中直到遇見負數為止。此時,停止數取數值,並自堆疊中取出(pop)五個數值並印出它們。如果堆疊中的元素個數小於五個,則印出錯誤訊息並停止執行。當印完五個數值後,再繼續讀取資料並放入堆疊中。當遇見檔案結尾時,印出訊息並把堆疊中的元素全部取出並印出。

用下列的資料來驗證程式:

1 2 3 4 5 -1 1 2 3 4 5 6 7 8 9 10 -2 11 12 -3 1 2 3 4 5

印出答案要為5 4 3 2 1 10 9 8 7 6 12 11 5 4 3 5 4 3 2 1 2 1)

1 Answer

Rating
  • Favorite Answer

    #include <stdio.h>

    #include <stdlib.h>

    typedef struct element * Link;

    struct element

    {

    int data;

    Link next;

    };

    Link push(Link head, int value)

    {

    Link newOne;

    newOne = (Link)malloc(sizeof(struct element));

    newOne->data=value;

    newOne->next=head;

    return newOne;

    }

    Link pop(Link head, int *value, int *flag)

    {

    if (head==NULL)

    {

    *flag=-1; //empty

    return head;

    }

    Link temp;

    temp=head;

    head=head->next;

    *value=temp->data;

    free(temp);

    flag=0;

    return head;

    }

    int main()

    {

    int num, flag, i;

    Link stack=NULL;

    FILE *fp;

    fp=fopen("c:\\test.txt","r");

    while (fscanf(fp,"%d", &num)!=EOF)

    {

    if (num <0)

    for (i=1;i<=5;i++)

    {

    stack=pop(stack, &num, &flag);

    if (flag==-1)

    {

    printf("Error! 堆疊已空,沒法Pop\n");

    return 1;

    }

    printf("%d ",num);

    }

    else

    {

    stack=push(stack,num);

    }

    }

    while (stack!=NULL)

    {

    stack=pop(stack, &num, &flag);

    printf("%d ",num);

    }

    printf("\n");

    system("pause");

    return 0;

    }

Still have questions? Get your answers by asking now.