刚刚学数据结构,有错误请大佬们指出并点拨一下(感谢!)。
学习这个链式的队列,好处是不需要考虑溢出的情况,方便,并且存储的数据够多,也不浪费空间。
功能
int InitQueue(LinkQueue *Q) //初始化
int ClearQueue(LinkQueue* Q) //清空
int EnQueue(LinkQueue *queue,int x) //入队
int DeQueue(LinkQueue* queue, int* x)//出队
int print(LinkQueue Q) //输出
大体上就这些主要的功能。
结构体
typedef struct QNode{
int data;
struct QNode* next;
}QNode,*SqQueue;
typedef struct {
SqQueue front;
SqQueue rear;
}LinkQueue;
1.初始化
我是弄了头节点p,然后把rear和front指向它。
int InitQueue(LinkQueue *Q) {
SqQueue p;
p= (SqQueue)malloc(sizeof(QNode));
assert(p != NULL); //assert(NULL!=p)的逻辑值为假时,程序终止运行
p->next = NULL;
Q->front = Q->rear = p;
Q->rear->next = NULL;
return TRUE;
}
2.清空
清空的话就是单链表的删除节点了,用p指代节点,free它
int ClearQueue(LinkQueue* Q) {
if (Q==NULL) {
printf("Queue为空!");
return FALSE;
}
SqQueue p = Q->front->next;
while (!Q) {
Q->front->next = p->next;
free(p);
p = Q->front->next;
}
Q->front = Q->rear;//清空后要把头尾同等一下,放在首位
return TRUE;
}
3.入队
int EnQueue(LinkQueue *queue,int x) {
SqQueue p;
p = (SqQueue)malloc(sizeof(QNode));
p->data = x;
p->next = NULL;
queue->rear->next = p;
queue->rear = p; //把queue->rear这个节点赋值给p
return TRUE;
}
4.出队
int DeQueue(LinkQueue* queue, int* x) {
if (!queue) {
printf("NULL");
return FALSE;
}
SqQueue p;
p = queue->front->next;
*x = p->data;
queue->front->next = p->next;
if (queue->rear == p) //要考虑只有一个数据的情况,帮头尾节点放一起
queue->rear = queue->front;
free(p);
return TRUE;
}
5.输出
int print(LinkQueue Q) {
QNode *p;
if (Q.front == Q.rear) {
printf("对为空!");
return FALSE;
}
p = Q.front->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
整体代码
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <assert.h>
typedef struct QNode{
int data;
struct QNode* next;
}QNode,*SqQueue;
typedef struct {
SqQueue front;
SqQueue rear;
}LinkQueue;
int InitQueue(LinkQueue *Q) {
SqQueue p;
p= (SqQueue)malloc(sizeof(QNode));
assert(p != NULL);
p->next = NULL;
Q->front = Q->rear = p;
Q->rear->next = NULL;
return TRUE;
}
int ClearQueue(LinkQueue* Q) {
if (Q==NULL) {
printf("Queue为空!");
return FALSE;
}
SqQueue p = Q->front->next;
while (!Q) {
Q->front->next = p->next;
free(p);
p = Q->front->next;
}
Q->front = Q->rear;
return TRUE;
}
int EnQueue(LinkQueue *queue,int x) {
SqQueue p;
p = (SqQueue)malloc(sizeof(QNode));
p->data = x;
p->next = NULL;
queue->rear->next = p;
queue->rear = p;
return TRUE;
}
int DeQueue(LinkQueue* queue, int* x) {
if (!queue) {
printf("NULL");
return FALSE;
}
SqQueue p;
p = queue->front->next;
*x = p->data;
queue->front->next = p->next;
if (queue->rear == p)
queue->rear = queue->front;
free(p);
return TRUE;
}
int print(LinkQueue Q) {
QNode *p;
if (Q.front == Q.rear) {
printf("对为空!");
return FALSE;
}
p = Q.front->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkQueue Q;
int x = 0;
InitQueue(&Q);
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
EnQueue(&Q, 4);
EnQueue(&Q, 5);
ClearQueue(&Q);
DeQueue(&Q, &x);
print(Q);
return 0;
}