链式队列
队列可以使用链表的形式来实现。相对于数组来说,使用链式存储结构来实现队列,在内存空间上没有数组的限制。
链式存储结构允许在入队或者出队时动态的分配内存,因此不会造成内存浪费或者超过限制内存的说法。

队列的创建
- 导入所需头文件
- 定义存储元素的数据结构Node包含两个成员data和next
- 定义两个指向数据节点的指针,并且置空(front=rae=NULL)
入队
- 创建一个newNode并给定一个值newNode->next=NULL
- 检查队列是否为空(rear==NULL)
- 如果为空,front=newNode和rear=newNode
- 如果不为空,设置rear->next=newNode和rear=newNode
void enQueue(int value){
struct Node *newNode;
newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=value;
newNode->next=NULL;
if (front==NULL){
front=rear=newNode;
}else{
rear->next=newNode;
rear=newNode;
}
printf("插入成功");
}
出队
- 创建一个newNode并给定值,然后newNode->next=NULL
- 检查队列是否为空(raer==NULL),终止并关闭
- 定义一个指针节点为temp=front
- 设置front=front->next,并释放temp,free(temp)
void dqQueue(){
if (front==NULL){
printf("下溢,队列为空");
}else{
struct Node *temp=front;
front=front->next;
printf("删除元素: %d \n",temp->data);
free(temp);
}
}
完整代码
struct Node{
int data;
struct Node *next;
} *front=NULL,*rear=NULL;
void enQueue(int value){
struct Node *newNode;
newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=value;
newNode->next=NULL:
if (front==NULL){
front=raer=newNOde;
}else{
rear->next=newNode;
rear=newNode;
}
printf("插入成功\n");
}
void deQueue(){
if (front==NULL){
printf("下溢,队列为空\n");
}else{
struct Node *temp=front;
front=front->next;
printf("删除元素:%d\n",temp->data);
free(temp);
}
}
void display(){
if (front==NULL){
printf("队列为空\n");
}else{
struct Node *temp=front;
while(temp->next!=NULL){
printf("%d--->",temp->data);
temp=temp->next;
}
printf("%d--->NULL\n",temp->data);
}
}
void main(){
int choice,value;
while(1){
printf("链队");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("输入你的选择");
scanf("%d",&chioce);
switch(chiose){
case 1:
printf("输入值被插入队列");
scanf("%d",&value);
enQueue(value);
break;
case 2:
deQueue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("输入错误,请重试");
}
}
}
更多内瓤,欢迎关注:
