您的位置:首页 > 其它

堆栈的链式表示和实现

2014-09-27 23:04 204 查看


#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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: