//链表实现
#ifndef _Stack_h
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack s);
Stack CreateStack();
void DisposeStack(Stack s);
void MakeEmpty(Stack s);
void Push(int x,Stack s);
int Top(Stack s);
void Pop(Stack s);
#endif
//head is dummy
struct Node{
int n;
PtrToNode Next;
};
int IsEmpty(Stack s){
return s->next == NULL;
}
Stack CreateStack(){
Stack s;
s = (Stack)malloc(sizeof(struct Node));
if(s == NULL){
printf("Out of Space!\n");
return 1;
}
s->n = 0;
s->next = NULL;
return s;
}
void DisposeStack(Stack s){
Stack p;
while(s!=NULL){
p = s-> next;
free(s);
s = p;
}
}
void MakeEmpty(Stack s){
if(s == NULL){
printf("Must create stack first!\n");
return 1;
}
while(!IsEmpty(s)){
Pop(s);
}
}
void Push(int x,Stack s){
Stack p;
p = (Stack)malloc(sizeof(struct Node));
if(p == NULL){
printf("Out of Space!\n");
return 1;
}
p->n = x;
p->next = s—>next;
s->next = p;
}
void Pop(Stack s){
Stack p;
if(IsEmpty(s)){
printf("Error:stack is empty!\n");
return 1;
}
p = s->next;
s->next = p->next;
free(p);
}
int Top(Stack s){
if(!IsEmpty(s))
return s->next->n;
printf("Stack is empty!\n");
return 1;
}
//数组实现
#ifndef _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty(Stack s);
int IsFull(Stack s);
Stack CreateStack(int MaxElements);
void DisposeStack(Stack s);
void MakeEmpty(Stack s);
void Push(int x,Stack s);
int Top(Stack s);
void Pop(Stack s);
int TopAndPop(Stack s);
#endif
//head is dummy
#define EmptyTOS -1
#define MinStackSize 5
struct StackRecord{
int capacity;
int topofstack;
int *a;
}
int IsEmpty(Stack s){
return s->topofstack == EmptyTOS;
}
int IsFull(Stack s){
return s->topofstack == MaxElements -1;
}
Stack CreateStack(int MaxElements){
Stack s;
if(MaxElements<MinStackSize){
printf("Stack size is too small\n");
return 0;
}
s = (Stack)malloc(sizeof(stuct StackRecord));
if(s == NULL){
printf("Out of Space!\n");
return 0;
}
s->a = (int *)malloc(sizeof(int)*MaxElements);
if(s->a == NULL){
printf("Out of Space\n");
return 0;
}
s->capacity = MaxElements;
MakeEmpty(s);
return s;
}
void DisposeStack(Stack s){
if(s!= NULL){
free(s->a);
free(s);
}
}
void MakeEmpty(Stack s){
s->topofstack = EmptyTOS;
}
void Push(int x,Stack s){
if(IsFull(s))
printf("Stack is Full\n");
s->a[++s->topofstack] = x;
}
int Top(Stack s){
if(!IsEmpty(s))
return s->[s->topofstack];
printf("Stack is Empty\n");
return 0;
}
void Pop(Stack s){
if(IsEmpty(s))
printf("Stack is Empty\n");
else s->topofstack--;
}
int TopAndPop(Stack s){
if(!IsEmpty(s))
return s->a[topofstack--];
printf("Stack is Empty\n");
return 0;
}