栈简单实现

// 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.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值