#include<iostream>
using namespace std;
typedef char DataType; //记得加分号
typedef struct snode
{
DataType x;
struct snode *next;
}SNode;
void Initiate(SNode **head)
{
(*head)=(SNode*)malloc(sizeof(SNode));
(*head)->next=NULL;
}
//入栈
void StackPush(SNode *head,DataType x)
{
if(head==NULL)
{
cout<<"error"<<endl;
return ;
}
SNode *p;
p=(SNode*)malloc(sizeof(SNode));
p->x=x;
p->next=head->next;
head->next=p;
}
//出栈
DataType StackPop(SNode *head)
{
if(head->next==NULL)
{
cout<<"the stack is empty"<<endl;
return NULL;
}
SNode *p;
DataType d;
p=head->next;
d=p->x;
head->next=p->next;
free(p);
return d;
}
//取得栈顶元素
DataType StackGet(SNode *head)
{
if(head->next==NULL)
{
cout<<"the stack is empty"<<endl;
return NULL;
}
return head->next->x;
}
void Destroy(SNode *head)
{
SNode *p,*p1;
p=head;
while(p->next!=NULL)
{
p1=p;
p=p->next;
free(p1);
}
}
int StackNotEmpty(SNode *head)
{
if(head->next==NULL) return 0;
else return 1;
}
void main()
{
SNode *stack;
Initiate(&stack);
StackPush(stack,'x');
cout<<StackGet(stack)<<endl;
StackPush(stack,'j');
StackPush(stack,'k');
cout<<StackPop(stack)<<endl;
cout<<StackPop(stack)<<endl;
cout<<StackPop(stack)<<endl;
cout<<StackPop(stack)<<endl; //由于链式栈没有元素,所以输出空
if(StackNotEmpty(stack)) cout<<"Not empty"<<endl;
else cout<<"empty!"<<endl;
Destroy(stack);
system("pause");
}
堆栈的链式表示和实现
最新推荐文章于 2023-07-05 16:11:31 发布