数据结构-顺序栈

栈分为链栈和顺序栈,分别和链表和顺序表挂钩
他们的结构分别的顺序表和单链表相似

#include<iostream>
#include<math.h>
#include<ctime>
#include<iomanip>
#include<stdlib.h>
#include<limits.h>//各种类型的范围库函数//常量库-2147483648   2147483647  
#include<assert.h>
#include<malloc.h>
using namespace std;
#define STACK_MAX_INT 10
typedef int elemtype;
typedef enum state{ ok = 1,error=2 };
typedef struct seqstack
{
	elemtype *data;
	int  maxsize;
	int top;
}seqstcck;

state initstack(seqstack &s)
{
	s.maxsize = STACK_MAX_INT;
	s.data = (elemtype*)malloc(sizeof(elemtype)*s.maxsize);
	memset(s.data, 0, sizeof(elemtype)*s.maxsize);
	if (s.data == NULL) return error;
	s.top = -1;
	return ok;
}
void destroystack(seqstack &s)
{
	free(s.data);
	s.data = NULL;
	s.maxsize = 0;
	s.top = -1;
}
void clearstack(seqstack &s)//不改变栈的容量
{
	s.top = -1;
}
int getsize(seqstack&s)
{
	return s.top + 1;
}
bool emptystack(seqstack&s)
{
	return getsize(s) == 0;
}
bool fullstack(seqstack&s)
{
	return getsize(s) == s.maxsize;
}
bool inc_size(seqstack&s)
{
	elemtype *newdata = (elemtype*)realloc(s.data, sizeof(elemtype)*s.maxsize*2);//要记得新建一个指针,如果内存不足realloc会失败从而导致数据丢失
	if (NULL == newdata)                                                         //为了避免这种情况需要新指针,从而确保原来数据不会消失
	{
		return false;
	}
	s.data = newdata;
	s.maxsize = s.maxsize * 2;
	return true;

}
void pushstack(seqstack&s, elemtype val)//入栈的顺序时先抬栈在入数据,top是栈顶
{
	if (!fullstack(s))
	{
		s.top += 1;
		s.data[s.top] = val;//两条语句可以合并写作为s.data[++s.top]
	}
	else
	{
		if (inc_size(s))
			pushstack(s, val);
		else cout << "内存不足无法增容" << endl;
	}
		
}
bool gettop(seqstack&s,elemtype&e)
{
	if (!emptystack(s))
	{
		e= s.data[s.top];
		return true;
	}
	else return false;
}
bool pop(seqstack&s, elemtype&e)
{
	if (!emptystack(s))
	{
		e = s.data[s.top];
		s.top -= 1;
		return true;
	}
	else return false;
}


/*
void main()
{
	seqstack mys;
	initstack(mys);
	pushstack(mys, 1);
	pushstack(mys, 2);
	pushstack(mys, 3);
	cout << mys.data[mys.top - 2];
	cout << mys.data[mys.top - 1];
	cout << mys.data[mys.top] << endl;
	elemtype x;
	while (pop(mys,x))
	{
		cout << x;
	}
}*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值