#include<stdio.h>
#include<malloc.h>
#define Data_Type int
typedef struct Stack{
//必须pBottom做头,否则将无法删除
struct Node * pBottom;
struct Node * pTop;
}STACK,* PSTACK;
typedef struct Node{
Data_Type data;
struct Node * pNext;
}NODE,* PNODE;
//初始化栈
bool initial(PSTACK);
//是否为空
bool isEmpty(PSTACK);
//遍历
void traverse(PSTACK);
//入栈
bool push(PSTACK,Data_Type);
//出栈 第二个参数为出栈的值
bool pop(PSTACK,Data_Type *);
int main(void){
Data_Type val;
STACK stack;
initial(&stack);
push(&stack,1);
push(&stack,2);
push(&stack,3);
push(&stack,4);
push(&stack,5);
pop(&stack,&val);
traverse(&stack);
printf("出栈的值为%d\n",val);
}
bool isEmpty(PSTACK pStack){
if(pStack->pBottom==pStack->pTop){
return true;
}else{
return false;
}
}
bool push(PSTACK pStack,Data_Type val){
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL==pNew){
return false;
}
pNew->data=val;
pNew->pNext=pStack->pTop;
pStack->pTop=pNew;
}
bool pop(PSTACK pStack,Data_Type * val){
if(isEmpty(pStack)){
return false;
}
*val = pStack->pTop->data;
PNODE pTemp = pStack->pTop;
pStack->pTop = pStack->pTop->pNext;
free(pTemp);
return true;
}
bool initial(PSTACK pStack){
pStack->pBottom = (PNODE)malloc(sizeof(NODE));
if(NULL==pStack->pBottom){
return false;
}
pStack->pBottom->pNext=NULL;
pStack->pTop = pStack->pBottom;
return true;
}
void traverse(PSTACK pStack){
PSTACK pTemp = pStack;
while(NULL!=pTemp->pTop->pNext){
printf("%d\n",pTemp->pTop->data);
pTemp->pTop =pTemp->pTop->pNext;
}
}
链表实现链式栈 c语言
最新推荐文章于 2020-08-06 20:41:53 发布