//链栈的设计与实现
//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));
}
}