【数据结构】顺序表与链式实现队列并测试

顺序表:

#pragma once
typedef char ElemType;
#define QueueSize 100
typedef struct Queue {
	ElemType queue[QueueSize];
	int front, rear;
}SeqQueue;

void InitQueue(SeqQueue *Q)
{
	Q->front = Q->rear = 0;
}

bool IsEmpty(SeqQueue Q)
{
	return (Q.front == Q.rear);
}

bool EnQueue(SeqQueue *Q, ElemType e)
{
	if (Q->front == (Q->rear+1)%QueueSize)
		return false;
	Q->queue[Q->rear] = e;
	Q->rear = (Q->rear + 1) % QueueSize;
	return true;
}

bool DeQueue(SeqQueue *Q, ElemType &e)
{
	if (Q->rear == Q->front)
		return false;
	else
	{
		e = Q->queue[Q->front];
		Q->front = (Q->front + 1) % QueueSize;
		return true;
	}
}

bool GetHead(SeqQueue Q, ElemType &e)
{
	if (Q.front == Q.rear)
		return false;
	else
	{
		e = Q.queue[Q.front];
		return true;
	}
}

void Clear(SeqQueue *Q)
{
	Q->front = Q->rear = 0;
}
//main()
#include"SeqQueue.h"
#include<iostream>

using namespace std;

void main()
{
	SeqQueue S;
	char str[] = "abcdefg", x;
	int i = 0;
	InitQueue(&S);
	for (i = 0; i < 8; i++)
	{
		EnQueue(&S, str[i]);
	}
	DeQueue(&S, x);
	cout << "front is " << x << endl;
	cout << "Queue is " << endl;
	if (!IsEmpty(S))
	{
		for (i = S.front; i < S.rear; i++)
		{
			cout << S.queue[i];
		}
	}
}

链式队列:

#pragma once
#include<iostream>

using namespace std;


typedef char ElemType;
typedef struct node {
	struct node *next;
	ElemType Data;
}LQnode,*QueuePtr;

typedef struct
{
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

void InitQueue(LinkQueue *L)
{
	L->front = L->rear =  new LQnode;
	if (!L->front)
		exit(-1);
	L->front->next = NULL;
}

bool IsEmpty(LinkQueue L)
{
	return (!(L.front->next));
}

bool EnQueue(LinkQueue *L, ElemType e)
{
	LQnode *s;
	s = new LQnode;
	if (!s) exit(-1);
	s->Data = e;
	s->next = NULL;
	L->rear->next = s;
	L->rear = s;
	return true;
}

bool DeQueue(LinkQueue *L, ElemType &e)
{
	LQnode *s;
	if (L->front == L->rear)
		return false;
	else
	{
		s = L->front->next;
		e = s->Data;
		L->front->next = s->next;
		if (L->rear == s) L->rear = L->front;
		delete s;
		return true;
	}
}

bool GetHead(LinkQueue *L, ElemType &e)
{
	LQnode *s;
	if (L->front == L->rear)
		return false;
	else
	{
		s = L->front->next;
		e = s->Data;
		return true;
	}
}

void Clear(LinkQueue *L)
{
	while (L->front)
	{
		L->rear = L->front->next;
		delete (L->front);
		L->front = L->rear;
	}
}
//main
#include"LinkQueue.h"

void main()
{
	LinkQueue s;
	InitQueue(&s);
	char *str = "abcdefg";
	int i = 0, l = 8;
	char e;
	for (i = 0; i < l; i++)
	{
		EnQueue(&s, str[i]);
	}
	GetHead(&s, e);
	cout << "Head is " << e << endl;
	cout << "Queue is" << endl;
	while (!IsEmpty(s))
	{
		DeQueue(&s, e);
		cout << e;
	}
	Clear(&s);
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值