我正在做这个程序它正常工作但唯一的问题是当int C的值是8位数时它使用320kib内存,我怎样才能最小化这个程序中的内存使用?
这是我的代码 的 1·; = Q&LT = POW(10,5) 的 1·=℃下= POW(10,7)
C程序
#include <stdio.h>
struct Stack{
int info;
struct Stack *next;
};
typedef struct Stack node;
node *start=NULL,*last,*neu;
推送()
void push(int x)
{
neu = (node *)malloc(sizeof(node));
neu->info = x;
neu->next = NULL;
if(start==NULL)
{
start = last = neu;
}
else
{
neu->next = last;
last = neu;
}
}
pop()方法
void pop() //updated
{ node *temp; //Updated
if(start==NULL)
{
printf("No Food\n");
}
else
{
printf("%d\n",last->info);
temp = last;
last = last->next;
free(temp);
}
}
主要()
int main()
{
int Q,type;
int C;
scanf("%d",&Q);
while(Q!=0)
{
scanf("%d",&type);
if(type == 1)
{
pop();
}
if(type == 2)
{
scanf("%d",&C);
push(C);
}
Q--;
}
return 0;
}
答案 0 :(得分:1)
好的,既然你似乎不理解我们的评论,我只是要实现我在这里说的话:
#include <stdio.h>
typedef struct Stack {
int info;
struct Stack * next;
} node, *pnode;
pnode top = NULL, // you only need the top pointer for a stack
pool = NULL; // the "pool" I mentioned
// allocate a new node
pnode get_new()
{
if (pool == NULL)
return malloc(sizeof(node));
pnode tmp = pool;
pool = pool->next;
return tmp;
}
// push operation
int push(int x)
{
pnode new = get_new();
if (new == NULL) // in case malloc fails
return 0;
new->info = x;
new->next = top;
top = new;
return 1;
}
// pop operation
pnode pop()
{
if (top == NULL)
return NULL;
pnode tmp = top;
top = top->next;
tmp->next = pool;
pool = tmp;
return tmp;
}
// factored out the printf stuff from your original pop
// since they are irrelevant to stack operations
void pop_orig()
{
pnode popped = pop();
if (pnode == NULL)
printf("No Food\n");
else
printf("%d\n", popped->info);
}
int main()
{
int Q, C, type;
scanf("%d", &Q);
while (Q > 0)
{
scanf("%d",&type);
if (type == 1)
{
pop_orig();
}
else
if (type == 2)
{
scanf("%d", &C);
if (push(C) == 0) {
printf("malloc failed - no memory left\n");
return 1;
}
}
Q--;
}
return 0;
}