栈(顺序栈和链式栈)

顺序栈

#include<stdio.h>
#include<iostream>
#include<assert.h>
#define INT_SIZE 10
using namespace std;
//顺序栈
typedef struct stack
{
	int* base;
	int top;//待入的地方
	int stacksize;//容量
}Stack,*Psatck;
void Init(Stack* ps)
{
	ps->base = (int*)malloc(sizeof(int)*INT_SIZE);
	assert(ps->base != NULL);
	ps->top = 0;
	ps->stacksize = INT_SIZE;
}
bool Isempty(Stack* ps)
{
	return ps->top == 0;
}
bool Isfull(Stack* ps)
{
	return ps->top == ps->stacksize;
}
void Inc(Stack* ps)
{
	ps->base = (int*)realloc(ps->base,sizeof(int) * ps->stacksize * 2);//两个参数,一个为之前的地址,另一个是最后一共需要的空间大小
	assert(ps->base != NULL);
	ps->stacksize *= 2;
}
bool Push(Stack* ps,int val)
{
	//需要判满
	assert(ps != NULL);
	if (Isfull(ps))
	{
		Inc(ps);
	}
	ps->base[ps->top++] = val;

	return true;
}

bool Pop(Stack* ps,int* rtval)
{
	assert(ps != NULL);
	if (Isempty(ps))
	{
		return false;
	}
	*rtval = ps->base[--ps->top];
	return true;
}
//获取栈顶元素
bool Top(Stack* ps, int* rtval)
{
	assert(ps != NULL);
	if (Isempty(ps))return false;
	*rtval = ps->base[ps->top - 1];
	return true;
}
int GetLength(Stack* ps)
{
	return ps->top;
}

void Clear(Stack* ps)
{
	ps->top = 0;
}
void Destroy(Stack* ps)
{
	free(ps->base);
	ps->base = NULL;
}
void Show(Stack* ps)
{
	for (int i = 0; i < ps->top; ++i)
	{
		printf("%d ", ps->base[i]);
	}
}
int main()
{
	Stack st;
	Init(&st);
	for (int i = 0; i < 20; ++i)
	{
		Push(&st, i + 1);
	}
	Show(&st);
	int rtval;
	Top(&st, &rtval);
	printf("%d\n", rtval);
	int tmp;
	Pop(&st, &tmp);
	printf("%d\n", tmp);
	Show(&st);
	return 0;
}

链式栈

#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;
typedef struct SNode
{
	int data;
	SNode* next;
}SNode,*PSNode;
void Init(SNode* ps)
{
	ps->next = NULL;
}
SNode* BuyNode()
{
	SNode* s = (SNode*)malloc(sizeof(SNode));
	memset(s, 0, sizeof(SNode));
	return s;
}
void Push(SNode* ps,int val)
{
	SNode* p = BuyNode();
	p->data = val;
	p->next = ps ->next;
	ps->next = p;
}
bool Pop(SNode* ps,int* rtval)
{
	assert(ps != NULL);
	if (ps->next != NULL)
	{
		SNode* p = ps->next;
		ps->next = ps->next->next;
		*rtval = p->data;
		return true;
	}
	return false;
}
bool Top(SNode* ps,int* rtval)
{
	assert(ps != NULL);
	if (ps->next != NULL)
	{
		SNode* p = ps->next;
		*rtval = p->data;
		return true;
	}
	return false;
}
void Clear(SNode* ps)
{
	SNode* p = ps->next;
	SNode* q = NULL;
	for (p; p!= NULL; p = p->next)
	{
		q = p;
		free(q);
	}
}

int main()
{ 
	SNode st;
	Init(&st);
	int rtval;
	for (int i = 0; i < 10; ++i)
	{
		Push(&st, i);
	}
	Top(&st, &rtval);
	printf("%d",rtval);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值