gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:47 27 4
gpt4 key购买 nike

目前我的代码使用堆栈并将用户输入的字符串一一插入堆栈。但是我想让它变得动态,我会 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++]='\0';

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("%s\n", 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 Underflow\n");
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;
}
}

关于C — 如何使我的堆栈完全动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com