栈满足先进后出原则(FILO),包括初始化(Init)、入栈(Push)、出栈(Pop)、清空(clear)、销毁(Destroy)、栈顶(Top)、计数(count)、是否有剩余(IsEmpty)八个基本函数,下面具体编写一下这八个基本函数。
在定义基本函数前要先定义栈的结构体保存栈的数据data与下一个节点next,再定义一个结构体里面存放栈类型的栈头pTop与计数器count;
typedef struct node
{
int data; //数据
struct node* next; //下一个节点
}Data;
typedef struct stack
{
int count;//计数
Data* pTop; //栈头
}Stack;
1.栈的初始化函数
void Init(Stack** STACK)
{
*STACK = (Stack*)malloc(sizeof(Stack));
(*STACK)->count = 0;
(*STACK)->pTop = NULL;
}
2.入栈
void Push(Stack* STACK, int num)
{
//栈为空时
if (STACK == NULL)
{
printf("stack is not exit!");
exit(1);
}
//定义中间变量
Data* temp = NULL;
temp = (Data*)malloc(sizeof(Data));
//头插法
temp->data = num;
temp->next = STACK->pTop;
STACK->pTop = temp;
STACK->count++;
}
3.出栈
void Pop(Stack* STACK)
{
//栈为空时
if (STACK == NULL)
{
printf("stack is not exit!");
exit(1);
}
//栈中数据清空使结束进程
if (STACK->count == 0) exit(1);
//标记头节点
Data* pDel = NULL;
pDel = (Data*)malloc(sizeof(Data));
pDel = STACK->pTop;
STACK->pTop = pDel->next;
free(pDel);
pDel = NULL;
STACK->count--;
}
4.清空
void clear(Stack* STACK)
{
if (STACK == NULL)
{
printf("stack is not exit.\n");
exit(1);
}
while (STACK->count!=NULL)
{
Pop(STACK);
}
}
5.销毁
void Destroy(Stack** STACK)
{
clear(*STACK);
free(*STACK);
*STACK = NULL;
}
6.栈顶
int Top(Stack* STACK)
{
if (STACK == NULL)
{
printf("stack is not exit.\n");
exit(1);
}
if (STACK->count == 0) exit(1);
return STACK->pTop->data;
}
7.计数
int count(Stack* STACK)
{
if (STACK == NULL)
{
printf("stack is not exit.\n");
exit(1);
}
return STACK->count;
}
8.是否有剩余
int IsEmpty(Stack* STACK)
{
if (STACK == NULL)
{
printf("stack is not exit.\n");
exit(1);
}
if (STACK->count == 0) return;
return STACK == NULL ? 1 : 0;
}
队列满足先进先出原则(FIFO),基本功能与栈一致,这里我主要编写一下初始化(Init)、入栈(Push)、出栈(Pop)函数;首先定义一个链表结构体存储队列的数据data与下一个节点next,再定义一个链式的头节点与尾节点;
typedef struct node
{
int data;
struct node* next;
}Data;
typedef struct queue
{
int count;
Data* pHead;
Data* pTail;
}Queue;
1.初始化
void Init(Queue** pQueue)
{
*pQueue = (Queue*)malloc(sizeof(Queue));
(*pQueue)->pHead = NULL;
(*pQueue)->pTail = NULL;
(*pQueue)->count = 0;
}
2.入栈
void Push(Queue* pQueue, int num)
{
//队列为空
if (pQueue== NULL)
{
printf("pQueue is not exit!");
exit(1);
}
//定义中间节点
Data* temp = NULL;
temp = (Data*)malloc(sizeof(Data));
temp->data = num;
temp->next = NULL;
//尾插法
if (pQueue->pHead == NULL)
{
pQueue->pHead = temp;
}
else
{
pQueue->pTail->next = temp;
}
pQueue->pTail = temp;
pQueue->count++;
}
3.出栈
int Pop(Queue* pQueue)
{
//队列为空
if (pQueue == NULL)
{
printf("pQueue is not exit!");
exit(1);
}
//标记队列头节点
Data* pDel = NULL;
pDel = pQueue->pHead;
int val = pDel->data;
//尾插法
pQueue->pHead = pDel->next;
pQueue->count--;
free(pDel);
pDel = NULL;
return val;
//队列为空时给尾结点赋空
if (pQueue->pHead == NULL)
{
pQueue->pTail = NULL;
}
}