数据结构_C_数组栈

数组栈,在数组顺序表的基础上,融合栈 头进尾出的特点,即只可以尾插尾删;另外,需要top一个结构体成员来记录栈顶位置,取栈顶元素和插、删数据!

Stack.h
#pragma once

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>

//栈:数组栈   栈的元素:数据,指针,栈顶;
//数组栈->尾插+尾删 ;top从0开始,先赋值后top++;

typedef struct stack {
	int* p;
	int capacity;
	int top;
}StackNode;

void InitStack(StackNode* head);

void StackPush(StackNode* head, int x);

void StackPop(StackNode* head);

int StackTop(StackNode* head);

bool Emp(StackNode* head);

void Display(StackNode* head);

void Destory(StackNode* head);
Stack.c
#include"stack.h"

//初始化
void InitStack(StackNode* head) {
	//head->data = 0;
	head->p = malloc(sizeof(StackNode)*4);
	if (head->p == NULL) {
		printf("malloc init failed \n");
		exit(-1);
	}
	head->top = 0;
	head->capacity = 5;
}

//压栈
void StackPush(StackNode* head, int x) {
	assert(head);
	//判断是否需要扩容
	if (head->top == head->capacity)
	{
		StackNode* tmp = malloc(sizeof(StackNode) * head->capacity * 2);
		if (tmp == NULL)
		{
			return printf("malloc failed\n");
			exit(-1);
		}
		else
		{
			head->p = tmp;
			head->capacity *= 2;
		}
	}
	//压栈 即尾插
	head->p[head->top] = x;
	head->top++;
}

//出栈
void StackPop(StackNode* head) {
	assert(head);
	assert(head->top > 0);
	head->top--;
}

//取栈顶元素
int StackTop(StackNode* head) {
	assert(head);
	return head->p[head->top-1];
}
//判断是否为空
bool Emp(StackNode* head) {
	assert(head);
	return head->top == 0;
}
//打印
void Display(StackNode* head) {
	assert(head);
	StackNode* cur = head;
	for (size_t i = 0; i < head->top; i++)
	{
		printf("%d,",cur->p[i]);
	}
	printf("\n");
}
//内存释放
void Destory(StackNode* head) {
	free(head->p);
	head->p == NULL;
	head->top = head->capacity = 0;
}

main.c
#include"stack.h"

void main() {
	StackNode s;
	InitStack(&s);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);

	Display(&s);
	StackPop(&s,3);
	StackPop(&s, 2);

	Display(&s);
	int res = StackTop(&s);
	printf("栈顶元素为:%d \n",res);
	bool b = Emp(&s);
	printf("%d",b);
	Destory(&s);


}

结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值