这个是栈的基本代码
#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;
}