数据结构- 栈和队列的实现

文章目录

采用数组实现

#include<iostream>
typedef int DataType;
using namespace std;
typedef struct Stack
{
	DataType* _array;
	int _top;// 表示有效元素个数 表示栈顶位置
	int _capcity;//栈容量
}Stack;

void StackInit(Stack* s)
{
	s->_array = (DataType*)malloc(sizeof(DataType));
	s->_top = 0;
	s->_capcity = 1;
}

void StackDestory(Stack* s)
{
	if (s->_array)
	{
		free(s->_array);
		s->_array = NULL;
		s->_top = 0;
		s->_capcity = 0;
	}
}

void StackPush(Stack* p, DataType data)
{
	//如果栈顶大于等于容量则扩容
	if (p->_top >= p->_capcity)
	{
		p->_array = (DataType*)realloc(p->_array, sizeof(DataType)*(2 * p->_capcity));
		p->_capcity *= 2;
	}
	p->_array[p->_top++] = data;
}

void StackPop(Stack* s)
{
	if (s->_top < 0)return;
	s->_top--;
}

DataType StackTop(Stack* s)
{
	return s->_array[s->_top - 1];
}

int StackEmpty(Stack* s)
{
	return s->_top == 0 ? 1 : 0;
}

int StackSize(Stack* s)
{
	return s->_top;
}

int main()
{
	
}


队列

队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头

采用链表实现

#include<iostream>
typedef int DataType;
using namespace std;
typedef struct Node
{
	DataType _data;
	struct Node* next;
}Node,*pNode;
typedef struct Queue
{
	pNode pHead;//队头
	pNode pTail;//队尾
};

pNode CreateNode(DataType data)
{
	pNode pNewNode = (pNode)malloc(sizeof(pNode));
	pNewNode->_data = data;
	pNewNode->next = nullptr;
	return pNewNode;
}

void QueueInit(Queue* q)
{
	q->pHead = nullptr;
	q->pTail = nullptr;
}

void QueuePush(Queue* q, DataType data)
{
	if (q->pHead == NULL)
	{
		q->pHead = q->pTail = CreateNode(data);
	}
	else
	{
		q->pTail->next = CreateNode(data);
		q->pTail = q->pTail->next;
	}
}

void QueuePop(Queue* q)
{
	pNode t = q->pHead;
	if (t != nullptr)
	{
		q->pHead = t->next;
		free(t);
	}

}

DataType QueueFront(Queue* q)
{
	return q->pHead->_data;
}

DataType QueueBack(Queue* q)
{
	return q->pTail->_data;
}

int QueueSize(Queue* q)
{
	int count = 0;
	pNode t = q->pHead;
	while (t != nullptr)
	{
		count++;
		t = t->next;
	}
	return count;
}
int QueueEmpty(Queue* q)
{
	return q->pHead == nullptr;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值