栈和队列的实现

栈的概念和结构

栈是一种特殊的线性表,只允许在固定的一端进行元素的插入和删除元素的操作。进行数据的插入和删除的操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵顼后进先出(Last In First Out)的规则。

压栈:栈的插入操作叫做压栈,也成为入栈、进栈。插入的数据在栈顶。

出栈:栈的删除操作叫做出栈。需要出栈的数据也是在栈顶。

栈的实现

栈的实现一般可以使用数组或者链表实现。相对而言,用数组实现栈要简单一些,因为数组尾插比较简单,而单链表尾插需要找尾。

和顺序表一样,栈也有静态栈和动态栈。下面实现以下动态栈。

代码如下:

void STInit(ST* pst)
{
	/*ST* tmp = (ST*)malloc(sizeof(ST));
	if (tmp == NULL)
	{
		perror("malloc");
		return;
	}*/
	pst->a = NULL;
	pst->top = -1;
	pst->capacity = 0;
}
void STPush(ST* pst, int x)
{
	assert(pst);
	if (pst->top == pst->capacity - 1)
	{
		int newcapacite = pst->capacity == 0 ? 4 : pst->capacity * 2;
		int* tmp = (int*)realloc(pst->a, newcapacite * sizeof(int));
		if (tmp == NULL)
		{
			perror("realloc");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacite;
	}
	pst->a[pst->top + 1] = x;
	pst->top++;
}
void STPop(ST* pst)
{
	assert(pst);
	pst->top--;
}
int STTop(ST* pst)
{
	assert(pst);
	if (pst->top == -1)
	{
		printf("此栈为空");
		return 1;
	}
	return pst->a[pst->top];
}
bool STEmpty(ST* pst)
{
	assert(pst);
	return pst->top == -1;
}
int STSize(ST* pst)
{
	assert(pst);
	return pst->top++;
}
void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->capacity = 0;
	pst->top = -1;

}

写下来发现还是很好写的。不过要注意栈顶top的初始取值,如果是-1的话,就是跟着数组的下标走的,如果是0的话,就是数组下标+1.

队列

队列的概念和结构

队列只允许在一端进行插入数据的操作,在另一端进行删除数据的特殊的线性表。队列是先进先出(First In First Out)。

队尾:像排队一样,数据插入的一端称为队尾。

队头:删除数据的一端称为队头。

队列的实现

和栈一样,队列也可以用数组和链表的结构实现。用链表实现比较简单一些,因为链表头删比较简单。

代码如下:

void QueueInit(Queue* pq)
{
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}
void QueuePush(Queue* pq, int x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc");
		return;
	}
	newnode->val = x;
	newnode->next = NULL;
	if (pq->ptail == NULL)
	{
		pq->ptail = pq->phead = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	Queue* del = pq->phead;
	pq->phead = pq->phead->next;
	free(del);
	if (pq->phead == NULL)
		pq->ptail = NULL;
	pq->size--;
}
int QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	return pq->phead->val;
}
int QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->ptail);
	return pq->ptail->val;
}
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead = NULL;
}
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}
void QueueDestroy(Queue* pq)
{
	assert(pq);
	QNode* cur = pq->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}

	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

有没有发现队列的头删特别简单,尾插也很简单,嘻嘻。

今天就到这里了捏!

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值