【数据结构】-栈和队列

1.栈的概念和结构

在这里插入图片描述
在这里插入图片描述

2.定义栈

typedef int SLDatatype;
typedef struct Stack{
SLDatatype *a;
int top;
int capacity;
}ST;

3.栈的初始化

void LNInit(ST *ps){
assert(ps);
ps->a=NULL;
ps->top=-1;//top指向栈顶元素
ps->capacity=0;
}

4.栈的销毁

void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

5.栈的插入(压栈)

void STPush(ST* ps, STDataType x)
{
	assert(ps);

	// ˣ 
	if (ps->top == ps->capacity)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		ps->a = tmp;
		ps->capacity = newcapacity;
	}

	ps->a[ps->top] = x;
	ps->top++;
}

6.栈的删除

void STPop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->top--;
}

7.取栈顶元素

STDataType STTop(ST* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	return ps->a[ps->top - 1];
}

8.栈的大小

int STSize(ST* ps)
{
	assert(ps);

	return ps->top;
}

9.判断栈是否为空

bool STEmpty(ST* ps)
{
	assert(ps);

	return ps->top == 0;
}

队列

1. 队列的定义和结构

在这里插入图片描述

2.定义队列

typedef int SLDatatype;
typedef struct QueueNode{
SLDatatype *a;
int val;
struct List*next;
}QNode;
struct Queue{
QNode*phead;
QNode*ptail;
};

3.入队列

void QueuePush(Queue*pq,QDatatype x){
assert(pq);
QNode* newnode=(QNode*)malloc(sizeof(QNode*));
if(newnode==NULL)
{
printf("malloc failed");
return;
}
if(pq->ptail){
pq->ptail->next=newnode;
pq->ptail=newnode;
}
else{
pq->phead=pq->ptail=newnode;
}
pq->size++;
}

4.出队列

void QueuePop(Queue*pq){
assert(pq);
assert(pq->phead!=NULL);
if(pq->phead==NULL){
free(pq->phead);
pq->phead=NULL;
}
else{
QNode*next=*pphead->next->val;
free(pq->pphead);
pq->phead=next;
}
pq->size--;
}

4.取队头值

QDataType QueueFront(Queue*pq){
assert(pq);
assert(pq->phead!=NULL);
return pq->phead->val;
}

5.判断是否为空

bool Empty(Queue*pq){
assert(pq);
return pq->size=0;
}
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值