如何使此堆栈代码使用更少的内存?(C郎)


#include<stdio.h>
int tp=-1;
void push(int arr[],int value)
{
arr[++tp]=value;
}
void pop(int arr[])
{
if(size()==0)
{
puts("-1");
return;
}
printf("%dn",arr[tp--]);
}
int size()
{
return tp+1;
}
void empty()
{
if(size()==0)puts("1");
else puts("0");
}
int top(int arr[])
{
if(size()==0)
{
puts("-1");
return;
}   
printf("%dn",arr[tp]);
}
int main()
{
int arr[10000];
unsigned int i,repeat;
char command[6];
scanf("%d",&repeat);                //repeating
for(i=0;i<repeat;i++)
{
scanf("%s",command);
switch(command[0])
{
case 'p':
if(command[1]=='u')         //push
{
int value;
scanf("%d",&value);
push(arr,value);
}
else pop(arr);              //pop. if stack is empty, output -1
break;
case 's':
printf("%dn",size());      //print size of stack
break;
case 'e':
empty();                    //if stack is empty, print 1. if not, print 0.
break;
case 't':
top(arr);                   //print value that is on top of stack. if stack is empty, print -1
break;
}
}

}

我想让这段代码使用更少的内存... 此代码使用 1116KB, 但是具有相同算法的代码使用 1000KB。 如何使此代码使用更少的内存?

这段代码的工作方式是这样的——

此代码有 5 个命令:

1.push X:在堆栈中添加X

2.pop :从堆栈中删除项目并打印。

3.尺寸:打印叠片的元素数量

4.空:如果此堆栈为空,则打印1。 如果不打印0

5.top:打印堆栈顶部的项目

步骤

  1. 输入值(重复循环量(

  2. 输入命令

  3. 利润!!

此问题可能有多种解决方案。由于您使用静态数组和顶级变量来跟踪堆栈的最后一个元素,因此最终算法的空间复杂性与数组大小每次都保持不变相同。

因此,在向堆栈添加任何元素时,您应该使用动态内存分配,这是指在每次添加位置时在 C 中使用 malloc 或 calloc 函数从堆中分配内存。而使用自由函数弹出元素并为其分配释放内存。

以下是使用链表实现堆栈的代码:

#include<stdio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
printf("1. Pushn2. Popn3. Displayn4. Exitn");
while(1){
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("nEnter value to insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("nWrong selection!!! n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("nInsertion is Success!!!n");
}
void pop()
{
if(top == NULL)
printf("nStack is Empty!!!n");
else{
struct Node *temp = top;
printf("nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("nStack is Empty!!!n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d",temp->data);
}
}   

您还可以在 codechef 的在线 IDE 中验证内存的使用情况,因为它使用的是 9432 KB。

最新更新