1.栈的初始化
typedef struct Node
{
int data;
struct Node *pNext;
}NODE ,*PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
void init(PSTACK pS)
{
pS->pTop=(PNODE)malloc(sizeof(NODE));
if(pS->pTop==NULL)
{
printf("动态内存分配失败\n");
exit(-1);
}
else
{
pS->pBottom=pS->pTop;
pS->pTop->pNext=nullptr;
}
}
2.栈的输入
void push(PSTACK pS,int val){
PNODE pNew=(PNODE)malloc(sizeof(NODE));
pNew->data=val;
pNew->pNext=pS->pTop;
pS->pTop=pNew;
}
3.栈的打印
void print(PSTACK pS)
{
PNODE ch=(PNODE)malloc(sizeof(NODE));
ch->pNext=pS->pTop;
while(1){
printf("%d ",ch->pNext->data);
ch->pNext=ch->pNext->pNext;
if(ch->pNext==pS->pBottom){
break;
}
}
}
4.栈的删除
bool pop(PSTACK pS,int *zh)
{
if(pS->pTop!=pS->pBottom){
PNODE ch=(PNODE)malloc(sizeof(NODE));
ch->pNext=pS->pTop;
*zh=pS->pTop->data;
pS->pTop=pS->pTop->pNext;
ch->pNext=NULL;
return true;
}
else{
return false;
}
}
5.主函数
int main(){
STACK S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
push(&S,5);
print(&S);
int zh;
pop(&S, &zh);
printf("删除的数是%d\n",zh);
print(&S);
return 0;
}