小编使用的编译器CLion。如有问题可以私信小编,有不懂得也可以私信哦。
双链表改进的队列
* 创建队列
* 创建节点
* 入队
* 出队
* 求队列长度
* 销毁队列
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* last;
struct Node* next;
}*QNode;
typedef struct Queue{
QNode front;
QNode fear;
int length;
}*DQueue;
/*创建队列*/
DQueue creatQueue()
{
DQueue q = (DQueue)malloc(sizeof(struct Queue));
q->front = q->fear = NULL;
q->length = 0;
return q;
}
/*创建节点*/
QNode creatNode(ElemType data)
{
QNode node = (QNode)malloc(sizeof(struct Node));
node->data = data;
node->next = node->last = NULL;
return node;
}
/*判断队列是否为空*/
int queueIsEmpty(DQueue q)
{
if(q->length == 0)
{
return 1;
}
return 0;
}
/*打印所有节点*/
void showQueue(DQueue q)
{
if(queueIsEmpty(q))
{
printf("队列为空!\n");
return;
}
QNode movenode = q->fear;
for(int i=0;i<q->length;i++)
{
printf("%d->",movenode->data);
movenode = movenode->next;
}
printf("\n");
}
/*求队列长度*/
int getLength(DQueue q)
{
return q->length;
}
/*入队*/
void appendNode(DQueue q,ElemType data)
{
QNode newnode = creatNode(data);
if(queueIsEmpty(q))
{
q->front = q->fear = newnode;
q->length++;
return;
}
newnode->next = q->fear;
q->fear->last = newnode;
q->fear = newnode;
q->length++;
}
/*出队*/
void removeNode(DQueue q)
{
if(queueIsEmpty(q))
{
printf("队列为空!\n");
return;
}
QNode delnode = NULL;
ElemType delnode_data;
if(q->length==1)
{
delnode = q->front;
delnode_data = delnode->data;
q->fear =q->front =NULL;
q->length--;
free(delnode);
}
else
{
delnode = q->front;
q->front = delnode->last;
q->front->next = NULL;
delnode_data = delnode->data;
q->length--;
free(delnode);
}
}
/*销毁队列*/
void destroy(DQueue q)
{
while(q->length!=0)
{
removeNode(q);
}
free(q); // ??????
printf("销毁成功!\n");
}
int main() {
return 0;
}