隊列的鏈式存儲,需要首先設計結點,包含一個指針域和一個數據域。然後對於一個隊列整體,設計出一個隊首指針和一個隊尾指針。隊首指針指向隊列的第一個元素。
存儲類型就可以描述爲:
typedef struct LinkNode{
ElemType data;
struct LinkNode *next;
}LinkNode;
typedef struct{
LinkNode *front;
LinkNode *rear;
}LinkQueue;
整體設計如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
typedef struct LinkNode{
ElemType data;
struct LinkNode *next;
}LinkNode;
typedef struct{
LinkNode *front;
LinkNode *rear;
}LinkQueue;
void InitQueue(LinkQueue &Q); //構造一個鏈式隊列
bool QueueEmpty(LinkQueue &Q); //判斷鏈隊是否爲空
void EnQueue(LinkQueue &Q,ElemType &x); //鏈隊隊尾插入元素
bool DeQueue(LinkQueue &Q,ElemType &x); //鏈隊刪除隊首元素
int main()
{
return 0;
}
void InitQueue(LinkQueue &Q){
Q.front=Q.rear=(LinkNode*)malloc(sizeof(LinkNode));
Q.front->next=NULL; //隊首指針與隊尾指針指向同一位置
}
bool QueueEmpty(LinkQueue &Q){ //判斷隊空
if(Q.front==Q.rear)
return true;
else
return false;
}
void EnQueue(LinkQueue &Q,ElemType &x){
LinkNode *p;
p=new LinkNode; //入隊時聲明一個p指針,插到隊尾
p->data=x;
p->next=NULL;
Q.rear->next=p; //插到隊尾處
Q.rear=p;
}
bool DeQueue(LinkQueue &Q,ElemType &x){
if(Q.front==Q.rear)
return false;
LinkNode *p;
p=Q.front->next;
x=p->data;
Q.front->next=p->next;
if(Q.rear==p) //若原隊列只有一個元素的時候
Q.rear=Q.rear; //刪除後變爲空
free(p);
return true;
}