實現順序隊列各種基本運算的演算法

來源:互聯網
上載者:User

/*algo3-4.cpp*/
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct qnode
{
 ElemType data;
 struct qnode *next;
}QNode;
typedef struct
{
 QNode *front;
 QNode *rear;
}LiQueue;
void InitQueue(LiQueue * &q)
{
 q=(LiQueue *)malloc(sizeof(LiQueue));
 q->front=q->rear=NULL;
}
void ClearQueue(LiQueue * &q)
{
 QNode *p=q->front,*r;
 if(p!=NULL)/*釋放資料結點佔用空間*/
 {
  r=p->next;
  while(r!=NULL)
  {
   free(p);
   p=r;r=p->next;
  }
 }
 free(q);/*釋放資料結點佔用空間*/
}
int QueueLength(LiQueue * &q)
{
 int n=0;
 QNode *p=q->front;
 while(p!=NULL)
 {
  n++;
  p=p->next;
 }
 return n;
}
int QueueEmpty(LiQueue *q)
{
 if(q->rear==NULL)
  return 1;
 else
  return 0;
}
void enQueue(LiQueue * &q,ElemType e)
{
 QNode *s;
 s=(QNode *)malloc(sizeof(QNode));
 s->data=e;
 s->next=NULL;
 if(q->rear==NULL)/*若鏈隊為空白,則新結點是隊首結點又是隊尾結點*/
  q->front=q->rear=s;
 else
 {
  q->rear->next=s;/*將*s結點鏈到隊尾,rear指向它*/
  q->rear=s;
 }
}
int deQueue(LiQueue * &q,ElemType &e)
{
 QNode *t;
 if(q->rear==NULL)/*隊列為空白*/
  return 0;
 if(q->front==q->rear)/*隊列中只有一個結點時*/
 {
  t=q->front;
  q->front=q->rear=NULL;
 }
 else/*隊列中有多個結點時*/
 {
  t=q->front;
  q->front=q->front->next;
 }
 e=t->data;
 free(t);
 return 1;
}

 

 

/*exp3-4.cpp*/
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct qnode
{
 ElemType data;
 struct qnode *next;
}QNode;
typedef struct
{
 QNode *front;
 QNode *rear;
}LiQueue;
extern void InitQueue(LiQueue * &q);
extern void ClearQueue(LiQueue * &q);
extern int QueueLength(LiQueue * &q);
extern int QueueEmpty(LiQueue *q);
extern void enQueue(LiQueue * &q,ElemType e);
extern int deQueue(LiQueue * &q,ElemType &e);
void main()
{
 ElemType e;
 LiQueue *q;
 printf("(1)初始化鏈隊\n");
 InitQueue(q);
 printf("(2)依次進鏈隊元素a,b,c\n");
 enQueue(q,'a');
 enQueue(q,'b');
 enQueue(q,'c');
 printf("(3)鏈隊為%s\n",(QueueEmpty(q)?"空":"非空"));
 if(deQueue(q,e)==0)
  printf("隊寬,不能出隊\n");
 else
  printf("(4)出隊一個元素%c\n",e);
 printf("(5)鏈隊q的元素個數:%d\n",QueueLength(q));
 printf("(6)依次進鏈隊元素d,e,f\n");
 enQueue(q,'d');
 enQueue(q,'e');
 enQueue(q,'f');
 printf("(7)鏈隊q的元素個數:%d\n",QueueLength(q));
 printf("(8)出鏈隊序列:");
 while(!QueueEmpty(q))
 {
  deQueue(q,e);
  printf("%c",e);
 }
 printf("\n");
 printf("(9)釋放鏈隊\n");
 ClearQueue(q);
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.