stack的简单实现

栈的性质:

比如函数调用的时候,程序里会记录函数发生调用的点的状态,为了调用结束后恢复状态;这时候就会用到栈;

先进后出。

#include <iostream>
#include <memory>
#include "stdio.h"
#include "malloc.h"

typedef int ElementType;

struct StackRecord{
	int Capacity;
	int Top;
	int* Array;
};

typedef StackRecord* Stack;
#define minElements 1

Stack CreateStack(int maxElements){
	Stack s = NULL;
	
	if (minElements > maxElements){
		printf("stack is too small\n");
		return s;
	}
	
	s = (Stack)malloc(sizeof(Stack));
	if (NULL == s){
		printf("s create failed\n");
		return s;
	}
	
	s->Capacity = maxElements;
	s->Top = -1;
	s->Array = (int*)malloc(s->Capacity * sizeof(int));
	if (s->Array == NULL){
		printf("s->Array create failed\n");
		free(s);
		s = NULL;
		return s;
	}
	
	return s;
}

bool IsEmpty(Stack s){
	return (s == NULL || s->Top == -1);
}

bool IsFull(Stack s){
	return s->Top == s->Capacity;
}

void Push(int val, Stack s){
	if (s == NULL){
		return;
	}
	
	if (IsFull(s)){
		printf("s is full with item:%d\n", val);
		return;
	}
	
	s->Array[++s->Top] = val;
}

void Pop(Stack s){
	if (s == NULL){
		return;
	}
	
	if (IsEmpty(s)){
		printf("s is empty\n");
		return;
	}
	
	--s->Top;	
}

int Top(Stack s){
	if (s == NULL){
		return -1;
	}
	
	if (IsEmpty(s)){
		printf("s is empty\n");
		return -1;
	}
	
	return s->Array[s->Top];
}

void Destory(Stack s){
	if (NULL == s){
		return;
	}
	
	if (s->Array){
		free(s->Array);
		s->Array = NULL;
	}
	
	free(s);
	s = NULL;
}
int main(){
	Stack s = CreateStack(10);
	Push(1, s);
	Push(2, s);
	
	printf("%d ", Top(s));
	Pop(s);
	printf("%d ", Top(s));
	
	Destory(s);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值