#include <stdio.h>
#include <stdlib.h>
typedef int QElemType;
typedef int Status;
typedef struct QNode{
QElemType data;
struct QNode*next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front; //队头指针,始终指向头结点
QueuePtr rear; //队尾指针,指向最后一个结点
int num;
}LinkQueue;
Status InitQueue(LinkQueue *s){
QueuePtr umi=(QueuePtr)malloc(sizeof(QNode));
s->front = s->rear = umi;
s->front->next = NULL;//将头指针置空
s->num = 0;
return 1;
}
Status ClearQueue(LinkQueue *umi){ //将队列清空
if (umi->front == umi->rear){
printf("Empty!\n");
return 0;
}
QueuePtr p;
p = umi->front->next;
while (umi->front != umi->rear){
umi->front = p->next;
free(p);
p = umi->front;
}
umi->front = 0;
return 1;
}
Status QueueEmpty(LinkQueue *umi){ //若队列为空返回1否则返回0
int yuki = 0;
if (!QueueLength(umi)){
yuki = 1;
}
return yuki;
}
Status QueueLength(LinkQueue *umi){ //返回队列的长度
return umi->num;
}
Status GetHead(LinkQueue *umi){ //返回队头元素
return umi->front->next->data;
}
Status EnQueue(LinkQueue *umi,QElemType e){ //插入元素e为队尾元素
QueuePtr s=(QueuePtr)malloc(sizeof(QNode));
s->data = e;
s->next = NULL;
umi->rear->next = s;
umi->rear = s;
umi->num++;
return 1;
}
Status DeQueue(LinkQueue *umi,QElemType *e){ //删除队头元素,并用e返回其值
if (umi->front == umi->rear){
printf("Empty!\n");
return 0;
}
QueuePtr p;
p = umi->front->next;
*e = p->data;
umi->front->next = p->next;
if (umi->rear == p) //若删去了最后一个元素,队尾指针指向头结点
umi->rear = umi->front;
free(p);
umi->num--;
return 1;
}
Status QueueTraverse(LinkQueue *umi){ //从队头到队尾进行访问
if (QueueEmpty(umi)){
printf("Empty!\n");
return 0;
}
QueuePtr p=umi->front->next;
while (p){
printf("%d\n", p->data);
p = p->next;
}
return 1;
}
int main(){
LinkQueue L;
int a;
InitQueue(&L);
EnQueue(&L, 1);
DeQueue(&L, &a);
QueueTraverse(&L);
/*if (QueueEmpty(&L)){
printf("Empty!");
}
else printf("Several");*/
}
优点:更容易插入和删除,只需要寻找到前驱结点即可;
缺点:不能随机存取元素,查找速度较慢;
总括:因为顺序表是一种随机存储结构,因此当线性表的操作主要是查找的时候,更加推荐顺序表;而进行插入和删除操作的时候更加推荐链表。