菜鸟制作......
head.h
#define OK 1
#define ERROR 0
#define STACKINITSIZE 100
#define STACKADD 10
typedef int SElemType;
typedef int Status;
typedef struct Node
{
SElemType data;
Node *next;
}SNode;
typedef struct
{
SNode *head;
SNode *rear;
}SqStack;
void show();
Status InitStack(SqStack &S);
Status DestroyStack(SqStack &S);
Status ClearStack(SqStack &S);
Status StackEmpty(SqStack &S);
int StackLength(SqStack S);
Status GetTop(SqStack &S,SElemType &e);
Status Push(SqStack &S,SElemType e);
Status Pop(SqStack &S,SElemType &e);
function.cpp
#include"head.h"
#include<iostream>
using namespace std;
void show()
{
cout<<"1.初始化栈!"<<endl;
cout<<"2.销毁栈!"<<endl;
cout<<"3.清空栈!"<<endl;
cout<<"4.栈是否为空!"<<endl;
cout<<"5.栈长!"<<endl;
cout<<"6.取栈顶!"<<endl;
cout<<"7.压栈!"<<endl;
cout<<"8.出栈!"<<endl;
}
Status InitStack(SqStack &S)
{
S.head=(SNode*)malloc(sizeof(SNode));
S.rear=S.head;
return OK;
}
Status DestroyStack(SqStack &S)
{
ClearStack(S);
free(S.head);
S.head=S.rear=NULL;
return OK;
}
Status ClearStack(SqStack &S)
{
if(S.head==NULL)
return ERROR;
SElemType e;
while(Pop(S,e))
{}
return OK;
}
Status StackEmpty(SqStack &S)
{
if(S.head==NULL)
return ERROR;
if(S.head==S.rear)
return OK;
return ERROR;
}
int StackLength(SqStack S)
{
if(S.head==NULL)
return ERROR;
int i=0;
SNode *p=S.head;
while(p!=S.rear)
{
i++;
p=p->next;
}
return i;
}
Status GetTop(SqStack &S,SElemType &e)
{
if(S.head==NULL)
return ERROR;
if(S.head==S.rear)
return ERROR;
e=S.head->next->data;
return OK;
}
Status Push(SqStack &S,SElemType e)
{
if(S.head==NULL)
return ERROR;
SNode *p=(SNode*)malloc(sizeof(SNode));
p->data=e;
p->next=S.head->next;
S.head->next=p;
if(S.head==S.rear)
S.rear=p;
return OK;
}
Status Pop(SqStack &S,SElemType &e)
{
if(S.head==NULL)
return ERROR;
if(S.head==S.rear)
return ERROR;
SNode *p=S.head->next;
e=p->data;
S.head->next=p->next;
free(p);
if(p==S.rear)
S.rear=S.head;
return OK;
}
main.cpp
#include"head.h"
#include<iostream>
using namespace std;
void main()
{
SqStack S;
int n;
SElemType e;
while(1)
{
show();
cin>>n;
switch(n)
{
case 1:{
if(!InitStack(S))
cout<<"初始化失败!"<<endl;
else
cout<<"初始化成功!"<<endl;
break;
}
case 2:{
if(!DestroyStack(S))
cout<<"销毁失败!"<<endl;
else
cout<<"销毁成功!"<<endl;
break;
}
case 3:{
if(!ClearStack(S))
cout<<"清空失败!"<<endl;
else
cout<<"清空成功!"<<endl;
break;
}
case 4:
{
if(S.head==NULL)
cout<<"栈不存在!"<<endl;
if(StackEmpty(S))
cout<<"栈为空!"<<endl;
else
cout<<"栈不为空!"<<endl;
break;
}
case 5:{
if(!StackLength(S))
cout<<"栈不存在!"<<endl;
else
cout<<"栈长为:"<< StackLength(S)<<endl;
break;
}
case 6:
{
if(!GetTop(S,e))
cout<<"获取失败!"<<endl;
else
cout<<"栈顶为:"<<e<<endl;
break;
}
case 7:{
cout<<"请输入要压入的数据:"<<endl;
cin>>e;
if(!Push(S,e))
cout<<"压入失败!"<<endl;
else
cout<<"压入成功!"<<endl;
break;
}
case 8:{
if(!Pop(S,e))
cout<<"出栈失败!"<<endl;
else
cout<<"出栈成功!出栈的数据为:"<<e<<endl;
break;
}
default:{cout<<"输入有误!请重新输入:"<<endl;break;}
}
}
}