队列的模板

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct Qnode{
   int data;
   Qnode *next;
}Qnode,*QueuePtr;
typedef struct{
  QueuePtr fronts;
  QueuePtr rear;
}LinkQueue;
void creat(LinkQueue &a){
   a.fronts=a.rear=(QueuePtr)malloc(sizeof(Qnode));
   a.fronts->next=NULL;
   return ;
}
void enQueue(LinkQueue &a,int e){
   QueuePtr p;
   p=(QueuePtr)malloc(sizeof(Qnode));
   p->data=e;
   p->next=NULL;
   a.rear->next=p;
   a.rear=p;
   return ;
}
void DestroyQueue(LinkQueue &a){
   while(a.fronts){
    a.rear=a.fronts->next;
    free(a.fronts);
    a.fronts=a.rear;
   }
}
void deQueue(LinkQueue a,int &e){
  if (a.fronts==a.rear)return;
  QueuePtr p;
  p=a.fronts->next;
  e=p->data;
  a.fronts->next = p->next;
  //if(a.rear==p)a.rear=a.fronts;
  free(p);
  return ;
}
int main(){
    LinkQueue a;
    creat(a);
    enQueue(a,1);
    enQueue(a,2);
    DestroyQueue(a);
    int data;
    deQueue(a,data);
    printf("%d\n",data);
    deQueue(a,data);
    printf("%d\n",data);
    return 0;
}

 

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct Qnode{
    int data;
    Qnode *next;
}Qnode,*Queue;
typedef struct {//相当于一个结构体指针,同时指向前面和后面
  Queue fronts;
  Queue rear;
}LinkQueue;
void init(LinkQueue &Q){//建立一个新的节点
   Q.fronts=Q.rear=(Queue)malloc(sizeof(Qnode));
   Q.fronts->next=NULL;
   return ;
}
void delete_queue(LinkQueue &Q,int e){//删除这个节点
  while(Q.fronts){//要是头结点仍然存在那么继续往后删除
    Q.rear=Q.fronts->next;
    free(Q.fronts);
    Q.fronts=Q.rear;//再次移动
  }
}
void inqueue(LinkQueue &Q,int e){//相当于链表的一样
   Queue p=(Queue)malloc(sizeof(Qnode));
   p->data=e;
   p->next=NULL;
   Q.rear->next=p;
   Q.rear=p;
}
void dequeue(LinkQueue &Q,int &e){
  if (Q.fronts==Q.rear)return;
  Queue p=Q.fronts->next;
  e=p->data;
  Q.fronts->next=p->next;
  if(Q.rear==p)Q.rear=Q.fronts;
  free(p);
  return ;
}
int main(){
  LinkQueue a;
  init(a);
  int n,tmp;
  scanf("%d",&n);
  for (int i=1;i<=n;i++){
    scanf("%d",&tmp);
    inqueue(a,tmp);
  }
  int s;
  for (int i=1;i<=n;i++){
    dequeue(a,s);
    printf("%d\n",s);
  }
  return 0;
}

 

posted @ 2018-12-27 23:34  bluefly-hrbust  阅读(322)  评论(0编辑  收藏  举报