栈(数组)和队列(链表)

栈和队列

栈是一种后进先出的结构,插入数据的一端称为栈顶,另一端称为栈底。插入数据称为圧栈(入栈),栈的删除称为出栈,出栈也在栈顶进行。

在这里插入图片描述

数组栈的实现

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STNodeType;

typedef struct STack
{
	STNodeType* _a;
	int _top;
	int _capacity;
}ST;

void StackInit(ST* ps)
{
	assert(ps);
	ps->_a = NULL;
	ps->_capacity = ps->_top = 0;
}

void Push(ST* ps, STNodeType val)
{
	assert(ps);
	//判断是否需要扩容
	if (ps->_top == ps->_capacity)
	{
		int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
		STNodeType* tmp = realloc(ps->_a, sizeof(STNodeType)*newcapacity);
		if (tmp == NULL)
		{
			printf("realloc ");
			exit(-1);
		}
		ps->_a = tmp;
		ps->_capacity = newcapacity;
	}
	ps->_a[ps->_top] = val;
	ps->_top++;
}

bool Empty(ST* ps)
{
	assert(ps);
	return ps->_top == 0;
}

void Pop(ST* ps)
{
	assert(ps);
	assert(ps->_top > 0);
	ps->_top--;
}

STNodeType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->_top > 0);
	return ps->_a[ps->_top - 1];
}

void Destroy(ST* ps)
{
	assert(ps);
	free(ps->_a);
	ps->_a = NULL;
	ps->_capacity = ps->_top = 0;
}

队列

队列仅允许在一段插入数据,在另一段删除数据的受限的线性表。具有先进先出的特点;入队列的一端称为队尾,出队列的一端称为队头。
在这里插入图片描述

队列可以通过链表实现也可以通过数组实现,使用链表实现效率会高一些,使用数组实现在出队列时,需要挪动数据。

队列的实现(链式)

#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int QDateType;

typedef struct QueueNode
{
	struct QueueNode* next;
	QDateType _val;
}QueueNode;

typedef struct Queue
{
	QueueNode* head;
	QueueNode* tail;
}Queue;

void QueueInit(Queue* pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;
}

void QueueDestory(Queue* pq)
{
	assert(pq);
	QueueNode* cur = pq->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

void QueuePush(Queue* pq, QDateType val)
{
	assert(pq);
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	newnode->_val = val;
	newnode->next = NULL;
	if (pq->head == NULL)
	{
		pq->tail = pq->head = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	QueueNode* next = pq->head->next;
	free(pq->head);
	pq->head = next;
	//如果删空了,需要将尾指针置空
	if (pq->head == NULL)
		pq->tail = NULL;
}

QDateType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->head->_val;
}

QDateType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->tail->_val;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->head == NULL;
}

size_t QueueSize(Queue* pq)
{
	size_t count = 0;
	QueueNode* cur = pq->head;
	while (cur)
	{
		count++;
		cur = cur->next;
	}
	return count;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值