#include <iostream>
using namespace std;
struct Stack{
int Data;
Stack *next;
};
Stack *CreateStack(){
Stack *PtrS =(Stack*)malloc(sizeof(Stack));
PtrS->next=NULL;
return PtrS;
}
void Push(Stack *PtrS,int num){
Stack *p =(Stack*)malloc(sizeof(Stack));
p->Data=num;
p->next=PtrS->next;
PtrS->next=p;
}
int Pop(Stack *PtrS){
if(PtrS->next==NULL){
cout<<"堆栈为空";
return -1;
}else{
Stack *HeadNode = PtrS->next;
PtrS->next=HeadNode->next;
int TopElem=HeadNode->Data;
free(HeadNode);
return TopElem;
}
}
void Print(Stack *PtrS){
if(PtrS->next==NULL){
cout<<"Stack is empty."<<endl;
}else{
Stack *p=PtrS;
while(p->next){
p=p->next;
cout<<p->Data<<' ';
}
cout<<endl;
}
}
int main()
{
Stack *stack =CreateStack();
Push(stack,1);
cout<<"Push(1): ";
Print(stack);
cout<<"Top :";
cout<<(stack->next->Data)<<endl;
Push(stack,2);
cout<<"Push(2): ";
Print(stack);
cout<<"Top :";
cout<<(stack->next->Data)<<endl;
Push(stack,3);
cout<<"Push(3): ";
Print(stack);
cout<<"Top :";
cout<<(stack->next->Data)<<endl;
cout<<"Pop: "<<Pop(stack)<<endl;
Print(stack);
cout<<"Pop: "<<Pop(stack)<<endl;
Print(stack);
cout<<"Pop: "<< Pop(stack)<<endl;
Print(stack);
return 0;
}
链式结构的堆栈
最新推荐文章于 2023-10-21 12:12:01 发布