您的位置:首页 > 理论基础 > 数据结构算法

数据结构之栈和队列---队列的基本操作

2015-08-03 17:00 746 查看
问题:实现队列的基本操作,内容包括队列的结构体,队列的初始化,队列的销毁,进队操作及出队操作

//队列节点的结构体

typedef struct QNode
{
ElemType data;
struct QNode *next;
}QNode, *QPoint;


//队列链的结构体

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


//队列的初始化

//lq->front分配空间时,类型为QPoint,但大小为QNode,不要把大小写成QPoint

LinkQueue* InitQueue()
{
LinkQueue *lq;
lq = (LinkQueue *)malloc(sizeof(LinkQueue));
lq->front = (QPoint)malloc(sizeof(QNode));
lq->rear = lq->front;
return lq;
}

//队列的销毁

void DestroyQueue(LinkQueue *lq)
{
while (lq->front)
{
lq->rear = lq->front->next;
free(lq->front);
lq->front = lq->rear;
}
free(lq);
}


//进队操作

//队首不存放元素

void EnQueue(LinkQueue *lq, ElemType elem)
{
QPoint qn = (QPoint)malloc(sizeof(QNode));
qn->data = elem;
qn->next = NULL;

lq->rear->next = qn;
lq->rear = qn;
}


//出队操作
int DeQueue(LinkQueue *lq, ElemType *elem)
{
QPoint tp;

tp = lq->front->next;
if(tp==NULL)
{
printf("队列为空\n");
return -1;
}

*elem = tp->data;
lq->front->next = tp->next;
<span style="white-space:pre">	</span>if(lq->rear==tp)
<span style="white-space:pre">		</span>lq->rear = lq->front;
free(tp);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息