Task:
Write routines for working with the stack. And then a program that just calls these routines in turn.
I wrote routines, but I cannot add an item to the stack using this routine. When I asked a question on one forum why the type does not work, I was told that I have some strange mixture of C and C++ that will never work, this completely confused me 🙁
Therefore, I ask here what is better to fix in these subroutines and how to add an element to the stack using them?
# include & lt; string.h & gt;
#include & lt; stdio.h & gt;
#include & lt; stdlib.h & gt;
#include & lt; stdint.h & gt;
typedef struct STACK
{
int info;
STACK * next;
};
int Empty (STACK * p)
{
if (p == NULL)
return 0;
else
return 1;
}
void Add (STACK ** p, int l)
{
STACK * tmp = new STACK;
tmp- & gt; info = l;
tmp- & gt; next = * p;
* p = tmp;
}
int Del (STACK ** p)
{
int j;
j = (* p) - & gt; info;
STACK * tmp = * p;
* p = (* p) - & gt; next;
delete tmp;
return j;
}
void Show (STACK * p)
{
STACK * tmp = p;
while (tmp! = NULL)
{
printf ("% d", tmp- & gt; info);
tmp = tmp- & gt; next;
}
}
void create (STACK ** u)
{
* u = NULL;
}
int main ()
{
{
STACK * STACK = NULL;
int num, l;
char otv;
printf ("% d how many items should I add?");
scanf ("% d", & amp; num);
for (int i = 0; i & lt; num; i ++)
Add (& amp; STACK, l);
printf ("% d Items added");
return;
}
}
Answer 1, authority 100%
Well, if you comb it a little – everything works … I didn’t fix the limiting cases, see for yourself – well, there, removal from an empty stack or something similar, because with your code, for example, when removing from an empty stack you will get some heartbeat 🙂
# include & lt; string.h & gt;
#include & lt; stdio.h & gt;
#include & lt; stdlib.h & gt;
#include & lt; stdint.h & gt;
typedef struct STACK_
{
int info;
struct STACK_ * next;
} STACK;
int Empty (STACK * p)
{
if (p == NULL)
return 0;
else
return 1;
}
void Add (STACK ** p, int l)
{
STACK * tmp = malloc (sizeof (* tmp));
tmp- & gt; info = l;
tmp- & gt; next = * p;
* p = tmp;
}
int Del (STACK ** p)
{
int j;
j = (* p) - & gt; info;
STACK * tmp = * p;
* p = (* p) - & gt; next;
free (tmp);
return j;
}
void Show (STACK * p)
{
STACK * tmp = p;
while (tmp! = NULL)
{
printf ("% d", tmp- & gt; info);
tmp = tmp- & gt; next;
}
puts ("");
}
void create (STACK ** u)
{
* u = NULL;
}
int main ()
{
STACK * STACK = NULL;
int num;
printf ("how many items should I add?");
scanf ("% d", & amp; num);
for (int i = 0; i & lt; num; i ++)
Add (& amp; STACK, i);
printf ("Items added");
Show (STACK);
Del (& amp; STACK);
Del (& amp; STACK);
Show (STACK);
}