// MyStack.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
using namespace std;
#define MAXLEN 50
// 数据准备
typedef struct{
char name[10];
int age;
}DATA;
typedef struct stack{
DATA data[MAXLEN + 1];
int top;
}StackType;
// init
StackType *STInit()
{
StackType *p = NULL;
if(p = (StackType *)malloc(sizeof(StackType)))
{
p->top = 0;
return p;
}
cout<<"malloc error!"<<endl;
return NULL;
}
// Empty
int STIsEmpty(StackType *s)
{
int t;
t = (s->top == 0);
return t;
}
// FULL
int STIsFull(StackType *s)
{
int t;
t = (s->top == MAXLEN);
return t;
}
// Clear
void STClear(StackType *s)
{
s->top = 0;
}
// Free
void STFree(StackType *s)
{
if(s)
{
free(s);
}
}
// push
int PushST(StackType *s, DATA data)
{
if((s->top + 1) > MAXLEN)
{
cout<<"stack is out!"<<endl;
return 0;
}
s->data[++s->top] = data;
return 1;
}
// pop
DATA PopST(StackType *s)
{
if(s->top == 0)
{
cout<<"stack is empty!"<<endl;
exit(0);
}
return (s->data[s->top--]); // 弹出当前元素,top --
}
// Peek 读取栈顶元素
DATA PeekST(StackType *s)
{
if (s->top == 0)
{
cout<<"stack is empty!"<<endl;
exit(0);
}
return (s->data[s->top]);
}
int main(int argc, char* argv[])
{
StackType *stack;
DATA data, data1;
stack = STInit();
assert(stack);
cout<<"Push: "<<endl;
cout<<"enter name age push: "<<endl;
do
{
cin>>data.name;
cin>>data.age;
if(strcmp(data.name, "0") == 0)
{
break;
}
else
{
PushST(stack, data);
}
} while (1);
do
{
cout<<"Pop"<<endl;
getchar();
data1 = PopST(stack);
cout<<data1.name<<data1.age<<endl;
} while (1);
STFree(stack);
return 0;
}
Push:
enter name age push:
tom 1
kang 2
lucy 3
0
0
Pop
lucy3
Pop
kang2
Pop
tom1
Pop
stack is empty!
Process returned 0 (0x0) execution time : 23.035 s
Press ENTER to continue.
// MyStack.cpp : Defines the entry point for the console application.//#include #include #include #include #include using namespace std;#define MAXLEN 50// 数据准备typedef struct{ char name