QUEUE——隊列(procedure)

來源:互聯網
上載者:User

#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

int main()
{
 int i;
 Type x;
 Type arr[] = {3,1,2,5,7,9};
 QUEUE *q = NULL;

 q = CreateQueue(10);
 if(NULL == q)
  return -1;
 
 for(i = 0; i < sizeof(arr)/sizeof(*arr); i++)
 {
  EnQueue(q, arr + i);
 }
 FrontQueue(q, &x);
 printf("x = %d\n", x);

 DisptoryQueue(q);
 return 0;
}
---------------------------------------------------------------

#ifndef _QUEUE_H__
#define _QUEUE_H__

struct node;
typedef int Type;
typedef struct node QUEUE;

QUEUE *CreateQueue(int);
void QueueMakeEmpty(QUEUE *);
int QueueIsEmpty(QUEUE *);
int QueueIsFull(QUEUE *);
int EnQueue(QUEUE *, const Type *);
int DeQueue(QUEUE *);
int FrontQueue(QUEUE *, Type *);
int FrontAndDeQueue(QUEUE *, Type *);
void DisptoryQueue(QUEUE *);

struct node{
 Type *data;
 int capacity;
 int front;
 int rear;
 int size;
};

#endif
-------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include "queue.h"

QUEUE *CreateQueue(int size)
{
 QUEUE *q = malloc(sizeof(*q));
 if(NULL == q)
  return NULL;
 q->data = malloc(sizeof(Type)*size); //隊列的長度,隊列的成員個數
 if(NULL == q->data)
 {
  free(q);
  return NULL;
 }
 q->capacity = size; //隊列容量
 QueueMakeEmpty(q);
 return q;
}
void QueueMakeEmpty(QUEUE *q)
{
 q->size = 0;
 q->front = 1;
 q->rear = 0;
}
int QueueIsEmpty(QUEUE *q)
{
 return q->size == 0;
}
int QueueIsFull(QUEUE *q)
{
 return q->size == q->capacity;
}
static int repeat(QUEUE *q, int rear) //隊列隊尾入隊,
{
 if(++rear == q->capacity)
  rear = 0;
 return rear;
}
int EnQueue(QUEUE *q, const Type *x)
{
 if(QueueIsFull(q))
  return -1;
 q->rear = repeat(q, q->rear); //每次入隊成功後,隊尾rear置0.
 q->data[q->rear] = *x;
 q->size++;
 return 0;
}
int DeQueue(QUEUE *q) //出隊
{
 if(QueueIsEmpty(q))
  return -1;
 q->front = repeat(q, q->front);
 q->size--;
 return 0;
}
int FrontQueue(QUEUE *q, Type *x) //查看隊首
{
 if(QueueIsEmpty(q))
  return -1;
 *x = q->data[q->front];
 return 0;
}
int FrontAndDeQueue(QUEUE *q, Type *x) //查看隊首並出隊
{
 if(FrontQueue(q, x) == 0)
  return DeQueue(q);
 return -1;
}
void DisptroyQueue(QUEUE *q)
{
 free(q->data);
 free(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.