一、栈
1.1栈的概念及结构
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端 称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
1.2栈的实现
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。以下是栈的C语言实现代码。
typedef int STDatatype;
typedef struct Stack
{
STDatatype* a;
int capacity;
int top;// 初始为0,表示栈顶位置下一个位置下标
}Stack;
void StackInit(Stack* ps)
{
ps->a = (Stack*)malloc(sizeof(Stack));
if (ps->a == NULL)
{
perror("malloc error:");
exit(-1);
}
ps->capacity = 4 ;
ps->top = 0;
}
void StackPush(Stack* ps, STDatatype x)
{
assert(ps);
if (ps->capacity == ps->top)
{
Stack* tmp = (Stack*)realloc(ps->a, ps->capacity * 2 * sizeof(Stack));
if (tmp == NULL)
{
perror("malloc error:");
exit(-1);
}
ps->a = tmp;
ps->capacity = ps->capacity * 2;
}
ps->a[ps->top] = x;
ps->top++;
}
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->top == 0;
}
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->top;
}
void StackDestory(Stack* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
STDatatype StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
二、队列
2.1队列的概念及结构
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出 FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头。
2.2队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数 组头上出数据,效率会比较低。
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int QueueDatatype;
typedef struct QListnode
{
struct QListnode* next;
QueueDatatype data;
}Qnode;
typedef struct Queue
{
Qnode* head;
Qnode* tail;
int size;
}Queue;
void QueueInit(Queue* q)
{
assert(q);
q->head = NULL;
q->tail = NULL;
q->size = 0;
}
void QueuePush(Queue* q, QueueDatatype x)
{
assert(q);
Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
if (newnode == NULL)
{
perror("malloc error:");
exit(-1);
}
newnode->next = NULL;
newnode->data = x;
if (q->tail == NULL)
{
q->head = newnode;
q->tail = newnode;
}
else
{
q->tail->next = newnode;
q->tail = newnode;
}
q->size++;
}
void QueuePop(Queue* q)
{
assert(q);
assert(!QueueEmpty(q));
if (q->head->next == NULL)
{
free(q->head);
q->head = q->tail = NULL;
}
else
{
Qnode* del = q->head;
q->head = q->head->next;
free(del);
}
q->size--;
}
bool QueueEmpty(Queue* q)
{
assert(q);
return q->head == NULL && q->tail == NULL;
}
QueueDatatype QueueFront(Queue* q)//获取队头元素
{
assert(q);
assert(!QueueEmpty(q));
//QueueDatatype ret =
return q->head->data;
}
QueueDatatype QueueBack(Queue* q)//获取队尾元素
{
assert(q);
assert(!QueueEmpty(q));
return q->tail->data;
}
int QueueSize(Queue* q)//队中的元素个数
{
assert(q);
return q->size;
}
void QueueDestory(Queue* q)
{
assert(q);
Qnode* cur = q->head;
while (cur)
{
Qnode* del = cur;
cur = cur->next;
free(del);
}
q->head = q->tail = NULL;
q->size = 0;
}