链式队列(Linked Queue)

链式队列


队列可以使用链表的形式来实现。相对于数组来说,使用链式存储结构来实现队列,在内存空间上没有数组的限制。

链式存储结构允许在入队或者出队时动态的分配内存,因此不会造成内存浪费或者超过限制内存的说法。

队列的创建


  1. 导入所需头文件
  2. 定义存储元素的数据结构Node包含两个成员data和next
  3. 定义两个指向数据节点的指针,并且置空(front=rae=NULL)

入队


  1. 创建一个newNode并给定一个值newNode->next=NULL
  2. 检查队列是否为空(rear==NULL)
  3. 如果为空,front=newNode和rear=newNode
  4. 如果不为空,设置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("插入成功");
}

出队


  1. 创建一个newNode并给定值,然后newNode->next=NULL
  2. 检查队列是否为空(raer==NULL),终止并关闭
  3. 定义一个指针节点为temp=front
  4. 设置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("输入错误,请重试");

        }
    }
}

更多内瓤,欢迎关注:


在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值