堆栈的链式存储
#include<iostream>
using namespace std;
typedef int ElementType;
typedef struct SNode* Stack;
struct SNode{
ElementType Data;
Stack Next;
};
Stack CreateStack();
int IsEmpty(Stack PtrS);
void Push(ElementType item,Stack PtrS);
ElementType Pop(Stack PtrS);
int main(){
Stack S=CreateStack();
Push(1,S);
Push(2,S);
Push(3,S);
Push(4,S);
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
cout<<Pop(S)<<endl;
Pop(S);
return 0;
}
Stack CreateStack(){
Stack PtrS=(Stack)malloc(sizeof(SNode));
PtrS->Next=NULL;
return PtrS;
}
int IsEmpty(Stack PtrS){
return (PtrS->Next==NULL);
}
void Push(ElementType item,Stack PtrS){
Stack newitem=(Stack)malloc(sizeof(SNode));
newitem->Next=PtrS->Next;
newitem->Data=item;
PtrS->Next=newitem;
}
ElementType Pop(Stack PtrS){
ElementType TopItem;
if(IsEmpty(PtrS)){
printf("栈空");
return NULL;
}else{
Stack S=PtrS->Next;
PtrS->Next=S->Next;
TopItem=S->Data;
free(S);
return TopItem;
}
}