I am working on this problem:
Stacks
Imagine, that you are employed by a software development company. You work now on the famous "D++ project", which is devoted to the creation of a new generation programming language. Your particular task is quite prosaic, though. You are to develop the memory manager being able to work with a large number of stacks.
Input
The first line of the input contains the total number of stack operations \$N\$, \$0 < N ≤ 100000\$. Each of the next \$N\$ lines contains a description of a stack operation, either in the form PUSH A B (meaning to push B into stack A), or in the form POP A (meaning to pop an element from stack A), where A is the number of stack (\$1 ≤ A ≤ 1000\$), and B is an integer (\$0 ≤ B ≤ 10^9\$). You may assume, that every operation is correct (i.e., before each POP operation, the respective stack is not empty).
Output
For each POP operation, described in the input, output the value, which this POP operation gets from the top of that stack, to which it is applied. Numbers should appear according to the order of the POP operations in the input. Each number should be output in a separate line.
I have developed a solution here:
#include<map>
class MyStack
{
public:
int data;
MyStack *link;
MyStack *top;
MyStack()
{
link = NULL;
top = NULL;
}
void push( int data )
{
MyStack * tmp = (MyStack *) malloc( sizeof( MyStack ) );
tmp->data = data;
tmp->link = top;
top = tmp;
}
void pop()
{
MyStack *tmp = top;
top = top->link;
printf( "%d\n", tmp->data );
free( tmp );
}
void clear()
{
while( top != NULL )
{
MyStack *tmp = top;
top = top->link;
free( tmp );
}
}
bool isEmpty()
{
return top == NULL;
}
};
int main()
{
static MyStack* stackPtrs[1001];
int noOfInstructions = 0;
scanf( "%d", &noOfInstructions );
char instruction[3];
short stackNumber = 0;
int stackValue = 0;
for( int inx = 0; inx < noOfInstructions; ++inx )
{
scanf("%s", &instruction );
scanf( "%hd", &stackNumber );
if( instruction[1] == 'U' )
{
scanf( "%d", &stackValue );
if( stackPtrs[stackNumber] == NULL )
{
MyStack *myStack = new MyStack();
myStack->push( stackValue );
stackPtrs[stackNumber] = myStack;
}
else
{
stackPtrs[stackNumber]->push( stackValue );
}
}
else
{
stackPtrs[stackNumber]->pop();
if( stackPtrs[stackNumber]->top == NULL )
{
stackPtrs[stackNumber] = NULL;
}
}
}
for( int inx =0; inx < 1001; ++inx )
{
if( stackPtrs[inx] != NULL )
{
stackPtrs[inx]->clear();
stackPtrs[inx] = NULL;
}
}
// Clear memory allocated here!.
return 0;
}
The memory limit for this question is around 0.75MB = 750KB. My program, out of 20-30 runs on an average is taking around 800KB, with 770KB being the least time.
Please suggest any improvements to this program.