链栈的设计与实现

//链栈的设计与实现
//2012-12-15
//author:@quanwei

#include<stdio.h>
#include<stdlib.h>
typedef struct stack{
	int data;
	struct stack *pNext;
}STACK;

/*************************************/
//函数名:	Push(STACK *top,int elem)
//参数:	STACK *top 栈顶指针
//			int elem 入栈元素
//作用:	将elem压入栈
//返回值:	成功则返回栈顶指针,失败则提示错误
/*************************************/
STACK *Push(STACK *top,int elem){
	STACK *stack = (STACK *)malloc(sizeof(STACK));
	if(stack == NULL) printf("ERROR!");
	stack->data = elem;
	stack->pNext = top->pNext;
	top->pNext= stack;
	return top;
}

/*************************************/
//函数名:	Pop(STACK *top)
//参数:	STACK *top 栈顶指针
//作用:	出栈
//返回值:	成功则返回出栈元素,失败则提示错误
/**************************************/
int Pop(STACK *top){
	if(top == NULL){
		printf("The stack is already empty");
		exit(1);
	}
	STACK *temp = top->pNext;
	int elem = temp->data;
	top->pNext = temp->pNext;
	return (elem);
}

/*************************************/
//函数名:	GgtTop(STACK *top)
//参数:	STACK *top 栈顶指针
//作用:	取栈顶元素
//返回值:	成功则返回栈顶元素,失败则提示错误
/**************************************/
int GetTop(STACK *top){
	if(top == NULL){
		printf("The stack is already empty");
		return 0;
	}
	return top->pNext->data;
}

/**************		测试程序	*******************/
void main(){
	STACK *stack = (STACK *)malloc(sizeof(STACK));			//建立栈
	STACK *top = stack;
	top->pNext = NULL;
	char ch = 'y';	
	int num;
	while(ch == 'y'){
		printf("Input element");
		scanf("%d",&num);
		fflush(stdin);
		Push(top,num);
		printf("go on?(y/n)");
		scanf("%c",&ch);
		fflush(stdin);
	}
	printf("The top element of the stack is:%4d",GetTop(top));
	printf("now pop stack\n");
	while(top->pNext!= NULL){
		printf("%4d",Pop(top));
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值