链表实现链式栈 c语言

#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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值