c判断数组是否为空_C语言栈的实现(链表和数组)

思想:

1、栈模型:基本操作有Push(入栈)和Pop(出栈),元素符合先进后出,即最先入栈的元素最后出栈。

2、链式:主要以链表的形式构成一个栈。入栈即是采用头插法构造链表(符合先进后出),出栈只要遍历链表即可,并记录栈顶元素。最后将链表释放。

3、数组:首先我们可以直接使用数组(array)构造栈,利用top(初始化为-1),元素进栈则top+1,array[top]=元素x,出栈top-1,出栈时记录栈顶元素。但是这样就伴随这一个问题,就是我们要提前声明数组的大小,如果申请空间过大,造成资源浪费。可以试用结构体来解决。结构体包括Capacity(容量),TopofStack(栈顶记录),array(数组)。

链式栈代码:

#include

结果:

7da662c27a8740c2c192c024f2e8788d.png

数组栈:

#include<stdio.h>
#include<stdlib.h>
#define Empty -1
#define MinStackSize 5
typedef struct StackRecord {
	int Capacity;
	int TopofStack;
	int* array;
}*Stack;
int IsEmpty(Stack S);//判断栈是否为空
int IsFull(Stack S);//判断栈是否已满
Stack CreateStack(int ElementDigits);//给数组分配合适的空间
void DisposeStack(Stack S);//释放栈
int MakeEmpty(Stack S);//置空栈
void Push(Stack S);
int Top(Stack S);
void Pop(Stack S);//置空栈
//初始化Top
int MakeEmpty(Stack S) {
	return S->TopofStack =Empty;
}
int IsEmpty(Stack S) {
	return S->TopofStack==Empty;
}
int IsFull(Stack S) {
	return S->TopofStack == S->Capacity;
}
//释放空间
void DisposeStack(Stack S) {
	if(S!= NULL) {
		free(S->array);
		free(S);
	}

	
}
//分配空间
Stack CreateStack(int ElementDigits) {
	Stack S;
	if (ElementDigits < MinStackSize) {//至少向栈中输入5个数
		printf("StackSize is too small");
		return 0;
	}
	S =(Stack)malloc(sizeof(struct StackRecord));
	if (S == NULL) {
		printf("out of space");
		return 0;
	}
	S->array = (int*)malloc(sizeof(int) * ElementDigits);
	if (S->array ==NULL) {
		printf("out of space");
		return 0;
	}
	S->Capacity = ElementDigits;
	MakeEmpty(S);
	return S;
}
//入栈
void Push(Stack S) {
	int x;
	if (IsFull(S)) {
		printf("stack is full");
	}
	for (int i = 0; i < S->Capacity; i++) {
		scanf_s("%d",&x);
		S->array[++S->TopofStack] = x;
	}
}
//返回栈顶元素
int Top(Stack S) {
	if (!IsEmpty(S)) {
		return S->array[S->TopofStack];
	}
	else {
		printf("empty stackt");
		return 0;
	}
}
//出栈
void Pop(Stack S) {
	int top;
	while (!IsEmpty(S)) {
		printf("%d出栈t", S->array[S->TopofStack--]);
		top=Top(S);
		printf("top is%dn",top);

	}
}
int main() {
	Stack S;
	int num;
	printf("输入入栈的个数:");
	scanf_s("%d", &num);
	S = CreateStack(num);
	Push(S);
	Pop(S);
	DisposeStack(S);
	return 0;
}

结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值