#include <stdio.h>
#include <stdlib.h>
struct LStack{
int data;
struct LStack* next;
};
struct LStack* createNode(int item){
struct LStack* tmp;
tmp = (struct LStack*)malloc(sizeof(struct LStack));
if(!tmp) return NULL;
tmp->next = NULL;
tmp->data = item;
return tmp;
}
struct LStack* init(){
struct LStack * tmp;
tmp = createNode(0);
return tmp;
}
int push(struct LStack* ls, int item){
struct LStack* tmp;
tmp = createNode(item);
if(!tmp) return 0;
tmp->next = ls->next;
ls->next = tmp;
return 1;
}
int isEmpty(struct LStack *ls){
return !ls || !(ls->next);
}
int pop(struct LStack* ls, int *pitem){
if(isEmpty(ls)) return 0;
struct LStack* tmp;
tmp = ls->next;
*pitem = tmp->data;
ls->next = tmp->next;
free(tmp);
return 1;
}
int main(){
struct LStack* ls;
ls = init();
for(int i=0; i<5; i++){
push(ls, i*2);
}
for(int i=0; i<8; i++){
int flag, item;
flag = pop(ls,&item);
printf("%d: %d--%d\n",i,flag,item);
}
return 0;
}
//注释部分为数组实现
/*
struct Stack{
int capacity;
int top;
int *data;
};
void Destroy(struct Stack *ps){
free(ps->data);
ps->capacity = -1;
ps->top = -2;
}
int Init(struct Stack *ps, int size){
ps->data = (int*)malloc(sizeof(int)*size);
ps->capacity = size;
ps->top = -1;
if(ps->data) return 1;
return 0;
}
int isFull(struct Stack *ps){
return ps->top==ps->capacity-1;
}
int Push(struct Stack *ps, int item){
if(isFull(ps)) return 0;
ps->top++;
ps->data[ps->top] = item;
return 1;
}
int isEmpty(struct Stack *ps){
return ps->top == -1;
}
int top(struct Stack *ps, int *pitem){
if(isEmpty(ps)) return 0;
*pitem = ps->data[ps->top];
return 1;
}
int pop(struct Stack *ps, int *pitem){
if(isEmpty(ps)) return 0;
*pitem = ps->data[ps->top];
ps->top--;
return 1;
}
int main(){
struct Stack s;
Init(&s,4);
int item;
for(int i=0; i<10; i++){
Push(&s,i*2);
top(&s,&item);
printf("%d: %d\n",i,item);
}
for(int i=0; i<10; i++){
int flag;
flag = pop(&s,&item);
printf("%d: %d,%d\n",i,flag,item);
}
return 0;
}
*/