1.设计思想:
我们可以设计出以上五种队列,但是基于时间复杂度,和空间复杂度的最优解,我们选择入队和出队均为O(1)的,也就是第五种
2.结构设计
typedef struct LPNode//数据节点
{int data;//数据struct LPNode* next;//后继指针
}LPNode;
typedef struct HNode//链式队列头节点
{ struct LPNode *front;//队头指针struct LPNode *rear;//队尾指针
}HNOde,*PLQueue;
3.链式队列的实现
//初始化
void InitQueue(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return;pq->front = NULL;pq->rear = NULL;
}//往队列中入数据(入队操作)
bool Push(PLQueue pq, int val)
{assert(pq != NULL);if (pq == NULL)return false;LPNode* p = (LPNode*)malloc(sizeof(LPNode));assert(p != NULL);给p数据//p->data = val;//插入p(处理尾节点)//p->next = pq->front;//pq->front = p;处理队头节点//if (pq->rear == NULL)//{// pq->rear = p;//}//return true;p->data = val;p->next = NULL;if (IsEmpty(pq)){pq->front = p;pq->rear = p;}else{pq->rear->next = p;//p插入队尾pq->rear = p;}return true;}//获取队头元素的值,但不删除
bool GetTop(PLQueue pq, int* rtval)
{assert(pq != NULL);if (pq == NULL)return false;if (IsEmpty(pq))return false;*rtval = pq->front->data;return true;
}//获取队头元素的值,并且删除
bool Pop(PLQueue pq, int* rtval)
{assert(pq != NULL);if (pq == NULL)return false;if (IsEmpty(pq))return false;*rtval = pq->front->data;LPNode* p = pq->front;pq->front = pq->front->next;free(p);if (pq->front == NULL)pq->rear = NULL;return true;
}//判空
bool IsEmpty(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return false;return pq->front == NULL;
}//获取队列中有效数据的个数
int GetLength(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return -1;int count = 0;for (LPNode* p = pq->front;p!=NULL; p = p->next){count++;/*if (p == pq->rear)break;*/}return count;
}//清空所有的数据
void Clear(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return;pq->front = NULL;pq->rear = NULL;
}//销毁
void Destroy(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return;LPNode* p = pq->front;free(p);p = p->next;
}void Show(PLQueue pq)
{assert(pq != NULL);if (pq == NULL)return;for (LPNode* p = pq->front;p!=NULL; p = p->next){printf("%d ", p->data);/*if (p == pq->rear)break;*/}printf("\n");
}
4.总结
1.带头结点,队头为第一个数据节点,队尾在最后一个数据节点
2.头结点为一个队头指针,一个队尾指针,增加队尾指针可以让入队时间复杂度为O(1)