队列的链式表示和实现

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct Qnode
{
ElemType data;
struct Qnode *next;
}Qnodetype;
typedef struct{
Qnodetype *front;
Qnodetype *rear;
}Lqueue;
void Lappend(Lqueue *q,int x);//初始化并建立队列
void creat(Lqueue *q)
{
    Qnodetype *h;
    int i,n,x;
    printf("输入将建立队列元素的个数:n=");
    scanf("%d",&n);
    h=(Qnodetype*)malloc(sizeof(Qnodetype));
    h->next=NULL;
    q->front=h;
    q->rear=h;
    for(i=1;i<=n;i++)
    {
        printf("链队列第%d个元素的值为:",i);
        scanf("%d",&x);
        Lappend(q,x);
    }
}
//入链队列
void Lappend(Lqueue *q,int x)
{
     Qnodetype *s;
     s=(Qnodetype*)malloc(sizeof(Qnodetype));
     s->data=x;
     s->next=NULL;
     q->rear->next=s;
     q->rear=s;
}//出链队列
ElemType Ldelete(Lqueue *q)
{
    Qnodetype *p;
    ElemType x;
    if(q->front==q->rear)
    {
        printf("队列为空!\n");
        return 0;
    }
    else
    {
        p=q->front->next;
        q->front->next=p->next;
        if(p->next==NULL)
        q->rear=q->front;
        x=p->data;
        free(p);
    }
    printf("出链队列元素:%d\n",x);return (x);
}
//遍历链队列
void display(Lqueue *q)
{
    Qnodetype *p;
    p=q->front->next;
    if(!p)  printf("队列为空!\n");
    else
    {
        printf("\n链队列元素依次为:");
        while(p!=NULL)
        {
            printf("%d-->",p->data);
            p=p->next;
        }
        printf("\n\n遍历链队列结束\n");

    }
}
int main()
{
    Lqueue *p;
    int x,cord;
    printf("\n**************第一次操作请选择初始化并建立队列!******************\n");
    do
    {
        printf("===============主菜单================\n");
        printf("       1 初始化并建立链队列  \n");
        printf("       2 入链队列  \n");
        printf("       3 出链队列  \n");
        printf("       4 遍历链队列  \n");
        printf("       5 结束程序运行  \n");
        printf("=====================================\n");
        scanf("%d",&cord);
        switch(cord)
        {
            case 1:{p=(Lqueue*)malloc(sizeof(Lqueue));
                    creat(p);
                    display(p);}break;
            case 2:{printf("请输入队列元素的值:x=");
                    scanf("%d",&x);
                    Lappend(p,x);
                    display(p);}break;
            case 3:{Ldelete(p);
                    display(p);}break;
            case 4:{display(p);}break;
            case 5:{exit(0);}
        }

    }while(cord<=5);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值