2021-05-27

这个是栈的基本代码
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

//栈的作用
//1.如果有后进先出的需求的函数
typedef int datatype;


typedef struct Stack
{
	datatype *_a;
	int _top; //栈顶
	int _capticy;

}Stack;
//初始化
void StackInit(Stack* pst)
{
	assert(pst);
	pst->_a = (datatype*)malloc(sizeof(datatype)*5);
	pst->_top = 0;
	pst->_capticy = 4;
}
//删除栈
void StackDestory(Stack* pst)
{
	assert(pst);
	free(pst->_a);
	pst->_a = NULL;
	pst->_capticy = pst->_top = 0;
}
//加入值
void Stackpush(Stack* pst, datatype x)
{
	assert(pst);
	//如果内存不足 就要加内存
	if (pst->_top == pst->_capticy)
	{
		pst->_capticy *= 2;
		datatype* tmp = (datatype*)realloc(pst->_a,  sizeof(datatype)*pst->_capticy);
		if (tmp == NULL)
		{
			printf("内存不足");
			exit(-1);
		}
		else
		{
			pst->_a = tmp;
		}
	}
	pst->_a[pst->_top] = x;
	pst->_top++;
}
//删除值
void Stackpop(Stack* pst)
{
	assert(pst);
	assert(pst->_top > 0);
		--pst->_top;
}
//求栈的元素个数
int Stacksize(Stack* pst)
{
	assert(pst);
	return pst->_top;
}
//返回1是空返回0是非空
int Stackempty(Stack* pst)
{
	assert(pst);
	return pst->_top == 0 ? 1 : 0;
}
//获取栈顶的数据
datatype Stacktop(Stack* pst)
{
	return pst->_a[pst->_top]; 
}
int main()
{
	Stack pst;
	StackInit(&pst);
	//一般输出的时候就是
	while (!Stackempty(&pst) == NULL)
	{
		printf("%d", Stacktop(&pst));
		Stackpop(&pst);
	}
	system("pause");
	return 0;
}

还有队列的代码

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#pragma warning (disable:4996)

typedef int QDatatype;
//结点

typedef struct QueueNode
{
	QDatatype data;
	struct Queue* next;
}QueueNode;

typedef struct Queue
{
	QueueNode* head;
	QueueNode* tail;
}Queue;
//初始化
void QueueInit(Queue* pst)
{
	assert(pst);
	pst->head = pst->tail = NULL;
}
//删除队列
void QueueDestory(Queue* pst)
{
	assert(pst);
	QueueNode* cur = pst->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pst->head = pst->tail = NULL;
}
//插入数据
void Queuepush(Queue* pst, QDatatype x)
{
	assert(pst);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		printf("内存不足");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pst->head == NULL)
	{
		pst->head = pst->tail = newnode;
	}
	else
	{
		pst->tail->next = newnode;
		pst->tail = newnode;
	}
}
//删掉数据
void Queuepop(Queue* pst)
{
	assert(pst);
	assert(pst->head);
	QueueNode* next = pst->head->next;
	free(pst->head);
	pst->head = next;
	if (pst->head == NULL)
	{
		pst->tail = NULL;
	}
}
//队头数据
QDatatype QueueFront(Queue* pst)
{
	assert(pst);
	assert(pst->head);
	return pst->head->data;
}
//队尾数据
QDatatype Queuebehead(Queue* pst)
{
	assert(pst);
	assert(pst->head);
	return pst->tail->data;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值