队列的基本操作

来源:互联网 发布:淘宝店卖古玩规则 编辑:程序博客网 时间:2024/04/20 02:02

/*
基础题

⑴编写链接队列的基本操作函数。
 ①进队操作 EnQueue(QUEUE **head,QUEUE **tail,int x)
 ②出队操作,队空 DeQueue(QUEUE **head,QUEUE **tail,int *cp)
 ③输出队列中元素 OutputQueue(QUEUE *head)
⑵调用上述函数
 ①调用进队函数建立一个队列。
 ②读取队列的第一个元数。
 ③从队列中删除元数。
 ④输出队列中的所有元数。
*/
//允许插入的一端叫队尾(rear),允许删除的一端叫队头(front)


  #include<stdio.h>
  #include<malloc.h>

  typedef struct queue
  {
 int data;
 struct queue *link;

  }QUEUE;

void EnQueue(QUEUE **head,QUEUE **tail,int x)
{
 QUEUE *p;
 p=(QUEUE*)malloc(sizeof(QUEUE));
 p->data=x;
 p->link=NULL;
 if(*head==NULL)
 *head=*tail=p;
 else
 {
  (*tail)->link=p;
  *tail=p;
 }
}

  int DeQueue(QUEUE **head,QUEUE **tail,int *cp)
  /*出队操作,队空*/
{
 QUEUE *p;
 p=*head;
 if(*head==NULL)
  return 1;
 *cp=(*head)->data;
 *head=(*head)->link;
 if(*head==NULL)
  *tail=NULL;
 free(p);
 return 0;
}

void OutputQueue(QUEUE *head)
/*输出队列中元素*/
{
 while(head!=NULL)
 {
  printf("%d",head->data);
  head=head->link;
 }
 printf("/n");
}


void main()
{
 QUEUE *head,*tail;
 int op,i;
 head=tail=NULL;  /*将队列,队首和队尾置空*/

 while(1)
 {
  printf("请选择操作,1:进队 2:出队 0:退出");
  fflush(stdin);
  scanf("%d",&op);
  switch(op)
  {
  case 0:
   return;
  case 1:
   printf("请输入进队元素:");
   scanf("%d",&i);
   EnQueue(&head,&tail,i);
   printf("队内元素为:/n");
   OutputQueue(head);
   break;
  case 2:
   if(DeQueue(&head,&tail,&i)==0)
   {
    printf("出队元素为:[%d],队内元素为:/n",i);
    OutputQueue(head);
   }
   else
    printf("队空/n");

  }

 }
}

原创粉丝点击