Home > Back-end >  Seek advice the order of the stack into the stack operation
Seek advice the order of the stack into the stack operation

Time:11-18

Out of the stack problem don't know how to change
The code is as follows:
#include
#include
# define maxsize 100
Typedef struct node {
Int stack [maxsize];
Int top;
} Seqstack;
Seqstack * initstack (Seqstack * s) {
S=(Seqstack *) malloc (sizeof (Seqstack));
if(! S)
There is insufficient space on the {printf (" \ n ");
return NULL; }
The else {s - & gt; Top=1;
Return s; }}
Push Seqstack * (Seqstack * s, int x) {if (s - & gt; Top==maxsize - 1)
{printf (" the stack is full \ n ");
return NULL; }
The else {s - & gt; Top++;
S - & gt; Stack [s - & gt; top]=x;
Return s; }}
Int pop (Seqstack * s)
{if (s - & gt; Top==1)
{printf (" empty stack \ n ");
return NULL; }
The else s - & gt; Top -;
The return of s - & gt; Stack [s - & gt; top + 1]; }
Void the display (Seqstack * s)
{if (s - & gt; Top==1)
{printf (" empty stack \ n "); }
The else {while (s - & gt; The top!=1)
{s - & gt; Top -; Printf (" % d - & gt;" That s - & gt; Stack [s - & gt; top + 1)); }}}
Void main ()
{Seqstack * s, * p;
int i;
Int a [6]={3,5,7,2,9,16};
S=initstack (s);
Printf (" stack, ");
for(i=0; i<6; I++)
S=push (s, a [I]);
The display (s);
Printf (" \ n stack: ");
While (s - & gt; The top!=1)
Printf (" % 4 d, "pop (s));
printf("\n"); }

CodePudding user response:

 # include & lt; Stdio. H> 
#include

# define maxsize 100

Typedef struct node {
Int stack [maxsize];
Int top;
} Seqstack;

Seqstack * initstack (Seqstack * s)
{
S=(Seqstack *) malloc (sizeof (Seqstack));
if(! S) {
There is insufficient space on the printf (" \ n ");
return NULL;
}
The else {s - & gt; Top=1;
Return s;
}
}
Push Seqstack * (Seqstack * s, int x)
{
If (s - & gt; Top==maxsize - 1)
{
Printf (" the stack is full \ n ");
return NULL; }
The else {
S - & gt; Top++;
S - & gt; Stack [s - & gt; top]=x;
Return s;
}
}

Int pop (Seqstack * s)
{if (s - & gt; Top==1)
{
Printf (" empty stack \ n ");
//return NULL;//why return NULL?
return -1;
}
The else
S - & gt; Top -;
The return of s - & gt; Stack [s - & gt; top + 1];
}
Void the display (Seqstack * s)
{
int i=0;

If (s - & gt; Top==1)
{
Printf (" empty stack \ n ");
}
The else {
While (I & lt; S - & gt; Top)
{
//s - & gt; Top -;
Printf (" % d - & gt;" That s - & gt; Stack [I]);
i++;
}
}
}

//void main ()
Int main ()
{Seqstack * s, * p;
int i;
Int a [6]={3,5,7,2,9,16};
S=initstack (s);
Printf (" stack, ");
for(i=0; i<6; I++)
S=push (s, a [I]);
The display (s);
Printf (" \ n stack: ");
While (s - & gt; The top!=1)
Printf (" % 4 d, "pop (s));
printf("\n");
}

For your reference ~

Reason is that the display function, this function has changed the top value, resulting in the stack when the top is 1, so there is no out of stack data,
In the display function, so do not modify the value of the top ~ just do the traversal
  • Related