栈和队列是计算机科学中非常重要的数据结构,它们在程序设计中有着广泛的应用。栈和队列都是一种线性数据结构,但它们的操作方式却有所不同。
一、栈
栈是一种后进先出(LIFO)的数据结构,它的操作包括入栈和出栈。入栈操作将一个元素压入栈顶,出栈操作则将栈顶元素弹出。
栈的应用非常广泛,比如在函数调用中,每次调用函数时都会将当前函数的状态保存在栈中,当函数返回时再将状态弹出,这样就可以实现函数的嵌套调用。
代码实现:
这里用到的是数组的方式实现栈。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#define E 20
typedef struct {
int *data;
int top;
int capacity;
} MyStack;
MyStack* myStackCreate() {//创建栈
MyStack *p = (MyStack*)malloc(sizeof(MyStack));
p->data = (int*)malloc(sizeof(int)*E);
p->capacity = E;
p->top = -1;
return p;
}
void myStackPush(MyStack* obj, int x) {//入栈
obj->top++;
if(obj->top >= obj->capacity){
obj->data = realloc(obj->data,obj->capacity*2);
obj->capacity = obj->capacity*2;
}
obj->data[obj->top] = x;
}
int myStackPop(MyStack* obj) {//删除栈顶元素
obj->top--;
return obj->data[obj->top+1];
}
int myStackTop(MyStack* obj) {//返回栈顶元素
return obj->data[obj->top];
}
bool myStackEmpty(MyStack* obj) {//判空
if(obj->top==-1)
return 1;
return 0;
}
void myStackFree(MyStack* obj) {//释放
obj->top=-1;
}
二、队列
队列与栈相反,是一种先进先出(FIFO)的数据结构。
代码实现:
这里用的是链表的方式来实现,没有用到哨兵位的头节点
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
typedef int QDateType;//队列存储数据类型
typedef struct QueueNode //队列元素节点
{
QDateType val;
struct QueueNode* next;
}QueueNode;
typedef struct Queue //队列
{
QueueNode* head;
QueueNode* end;
int size;
}Queue;
void QueueInti(Queue** qqu){// 队列初始化
*qqu = (Queue*)malloc(sizeof(Queue));
(*qqu)->end = (*qqu)->head = NULL;
(*qqu)->size = 0;
}
void QueueDestory(Queue* qu){// 队列的销毁
assert(qu);
QueueNode *cur,*t;
cur = qu->head;
while(cur){
t = cur;
cur = cur->next;
free(t);
}
qu->end = qu->head = NULL;
qu->size = 0;
}
void QueuePush(Queue* qu, QDateType x){// 入队
assert(qu);
QueueNode *p = (QueueNode*)malloc(sizeof(QueueNode));
p->val = x;
p->next = NULL;
if(qu->end == NULL){
qu->head = qu->end = p;
}
else
{
qu->end->next = p;
qu->end = p;
}
qu->size++;
}
void QueuePop(Queue* qu){// 出队
assert(qu);
QueueNode *next;
assert(qu->head);
next = qu->head->next;
if(next == NULL){
free(qu->head);
qu->head = qu->end = NULL;
}
else{
free(qu->head);
qu->head = next;
}
qu->size--;
}
QDateType QueueFront(Queue* qu){// 取出队首元素
assert(qu);
assert(qu->head);
return qu->head->val;
}
int QueueSize(Queue* qu){// 求队列的长度
return qu->size;
}
bool QueueEmpty(Queue* qu){// 判断队是否为空
if(qu->size==0)
return true;
else
return false;
}