C — 如何使我的堆栈完全动态



目前我的代码使用堆栈并将用户输入的字符串逐个推送到堆栈中。但是我想让它动态化,我会 malloc/realloc,我知道我错过了一些完全明显的东西,但我想我有隧道视觉......帮助?

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
char a [MAXSIZE];
char * p = a;
int top = -1;
void push ( char n )
{
    if ( top == 99)
    {
        printf( "stack overflow");
        return;
    }
    top+=1;
    a[top] = n;
}

/*  Function to delete an element from the stack */
void pop(){
    if(top == -1)
        printf("Stack is Empty");
    else
        top-=1;
}
char *inputString(FILE* fp, size_t size){
    //The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != 'n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(char)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='';
    return realloc(str, sizeof(char)*len);
}
int balanced (char * m){
    int size = sizeof(m);
    int i, j;
    for (i=0; i<=size; ++i){
        push(m[i]);
    }
}
int main(void){
    char *m;
    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%sn", m);
    balanced(m);
    int i;
    for (i=0;i<=sizeof(a);++i){
        printf("n%c", a[i]);
    }
    free(m);
    return 0;
}

如果我正确理解你的问题,这就是你应该做的。

struct Stack
{
    char c;
    struct Stack *next;
}*stack = NULL;
char pop()
{
    if(stack == NULL)
    {
        printf("Stack Underflown");
        return NULL;
    }
    c = stack -> c;
    struct Stack * temp = stack;
    stack = stack -> next;
    free(temp);
    return c;
}
void push(char c)
{
    struct Stack * temp = malloc(sizeof(struct Stack));
    temp -> next = NULL;
    temp -> c = c;
    if (stack == NULL)
        stack = temp;
    else
    {
        temp -> next = stack;
        stack = temp;
    }
}

相关内容

  • 没有找到相关文章