Home > Back-end >  Chain stack problem
Chain stack problem

Time:02-16

#include
#include
#include
# define Stack_ElemType int
Typedef struct StackNode {
Struct StackNode * next;
Stack_ElemType data;
} StackNode, * LinkStack;
//chain stack initialization//return is the address of the first chain stack
StackNode * initStack (LinkStack S) {
S=(LinkStack) malloc (sizeof (StackNode));
If (S==NULL) {
Printf (" memory allocation is not successful! \n");
return 0;
};
S - & gt; Next=NULL;
Return S;
};
//create a chain stack
StackNode * CreatStack (LinkStack S) {
StackNode * p;
Int j=1;
Stack_ElemType t=0;
While (j) {
Printf (" please enter the top element, input 1 end create \ n ");
Scanf_s (" % d ", & amp; T);
If (t==1) {
break;
}
P=(LinkStack) malloc (sizeof (StackNode));
If (p==NULL) {//dynamically allocated space should judge otherwise there will be a warning after
Printf (" memory allocation is not successful! \n");
return 0;
};
P - & gt; Data=https://bbs.csdn.net/topics/t;
P - & gt; Next=S;
S=p;
};

Return S;
}
//chain stack pressure stack
Void pushStack (LinkStack & amp; S, Stack_ElemType e) {
StackNode * p;
P=(LinkStack) malloc (sizeof (StackNode));
If (p==NULL) {//dynamically allocated space should judge otherwise there will be a warning after
Printf (" memory allocation is not successful! \n");
return;
}
P - & gt; Data=https://bbs.csdn.net/topics/e;
P - & gt; Next=S;
Printf (" % d \ n ", p - & gt; The data);
S=p;//for just now stack pressure stack node of p

};
StackNode * popStack (LinkStack S, Stack_ElemType * e) {
StackNode * p;
If (S==NULL) {
return 0;
}
* e=S - & gt; The data;
P=S;
S=S - & gt; Next;
Free (p);
Return S;
};

Stack_ElemType StackLenth (StackNode S) {
Int I=1;
StackNode * p;
P=S.n ext.
While (p) {
P=p - & gt; Next;
I++;
};
return i;
}
Int main (void) {
StackNode * S;
S=NULL;
Stack_ElemType j=0;
S=initStack (S);
 S=CreatStack (S); 

For (int I=0; I & lt; 5; I++) {
S=popStack (S, & amp; J);
Printf (" % d \ n ", j);
};
S=popStack (S, & amp; J);
Printf (" % d \ n ", j);
return 0;
}





Excuse me why I add red font in this function to change the S address is when you return to function have been released p address?
But I returned to the S address to continue
  • Related