# 数据结构与算法-链式队列

### 链式队列的定义

#### 链式队列的结构

``````#define OK 1
#define ERROR 0
#define TURE 1
#define FLASE 0

typedef int Status;
typedef int ElemType;
//结点
typedef struct SqNode{
ElemType data;
struct SqNode *next;
}SqNode, *SqQueuePtr;
//结构
typedef struct Queue{
SqQueuePtr front;
SqQueuePtr rear;

#### 链式队列的初始化

``````//初始化
Q->front = Q->rear = (SqQueuePtr)malloc(sizeof(SqNode));

if (!Q->front) return ERROR;
Q->front->next = NULL;//头结点置空
return OK;
}

#### 链式队列的销毁

``````//销毁队列

while (Q->front) {
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}

return OK;
}

#### 链式队列的清空

``````//置空
SqQueuePtr p,temp;
//清空
Q->rear = Q->front;
p = Q->front->next;
Q->front->next = NULL;

//删除内存
while (p) {
temp = p->next;
p = temp;

free(temp);
}

return OK;
}

#### 判断链式队列是否为空

``````//判断队列是否为空

if (Q.front == Q.rear) {
return OK;
}

return ERROR;
}

#### 获取链式队列的长度

``````//长度

int i = 0;
SqQueuePtr p;
p = Q.front;
while (p != Q.rear) {
p = p->next;
i++;
}
return i;
}

#### 链式队列的入队操作

``````//入队
SqQueuePtr temp = (SqQueuePtr)malloc(sizeof(SqNode));

if (!temp) return ERROR;

temp->data = data;
temp->next = NULL;

Q->rear->next = temp;
Q->rear = temp;

return OK;
}

#### 链式队列的出队操作

``````//出队

SqQueuePtr temp;

temp = Q->front->next;

*e = temp->data;
Q->front->next = temp->next;

if (Q->rear == temp) {
Q->rear = Q->front;
}

free(temp);

return OK;
}

#### 链式队列的对头元素

``````Status GetTopValue(LinkQueue Q, ElemType *e){

*e = Q.front->next->data;

return OK;
}

#### 链式队列的遍历

``````void printLinkQueue(LinkQueue Q){

printf("打印链式队列\n");

SqQueuePtr temp;

temp = Q.front->next;

while (temp) {
printf("%d  ",temp->data);
temp = temp->next;
}
printf("\n");
}

``````int main(int argc, const char * argv[]) {
// insert code here...
printf("链式队列，go go go!\n");

ElemType data;

printf("插入队列\n");
for (int i = 1; i < 6; i++) {
}
}

printf("出队一个元素\n");
printf("出队元素为%d\n",data);
GetTopValue(Q, &data);
printf("对头元素为:%d\n",data);
return 0;
}

``````链式队列，go go go!

1  2  3  4  5

Program ended with exit code: 0