c/c++線性迴圈佇列

小石王發表於2018-06-30

線性迴圈佇列

佇列是先進先出,和棧相反.

線性迴圈佇列,犧牲一個空間,實現迴圈。比如空間大小為4,犧牲一個空間,所以最多放3個元素。

假設front指向0位置,tail指向3位置

1 2 3

出隊後

front指向1位置,tail位置不變還是3

2 3

入隊後(4)

front指向不變還是1,tail指向0位置

2 3 4

出隊後

front指向2位置,tail位置不變還是0

3 4

入隊後(5)

front指向不變還是2,tail指向1位置

5 3 4

whilequeue.h

#ifndef __WHILEQUEUE__
#define __WHILEQUEUE__

#include <stdio.h>
#include <malloc.h>
#include <assert.h>
#include <memory.h>
#include <stdbool.h>

#define WHILEQUEUE_INIT_SIZE 8

typedef int ElemType;

typedef struct whilequeue{
  ElemType* base;
  int front;
  int tail;
}whilequeue;

void init(whilequeue*);
//入隊
void enQueue(whilequeue*, ElemType);
void show_list(whilequeue*);
//出隊
void deQueue(whilequeue*);
void clear(whilequeue*);
void destroy(whilequeue*);
#endif

whilequeue.c

#include "whilequeue.h"

void init(whilequeue* seq){
  seq->base = (ElemType*)malloc(sizeof(ElemType) * WHILEQUEUE_INIT_SIZE);
  seq->front = seq->tail = 0;
}
void enQueue(whilequeue* seq, ElemType x){
  //判斷佇列是否已滿
  if((seq->tail + 1) % WHILEQUEUE_INIT_SIZE == seq->front){
    printf("queue is full
");
    return;
  }
  seq->base[seq->tail] = x;
  seq->tail = (seq->tail + 1) % WHILEQUEUE_INIT_SIZE;
}
void show_list(whilequeue* seq){
  int i = seq->front;
  while(i != seq->tail){
    printf("%d
", seq->base[i++ % WHILEQUEUE_INIT_SIZE]);
    i = i % WHILEQUEUE_INIT_SIZE;
  }
}
void deQueue(whilequeue* seq){
  //判斷佇列是否為空,空了的話,就不需要移動front
  if(seq->front == seq->tail)return;
  seq->front = (seq->front + 1) % WHILEQUEUE_INIT_SIZE;
}
void clear(whilequeue* seq){

}
void destroy(whilequeue* seq){

}

whilequeuemain.c

#include "whilequeue.h"

int main(){
  whilequeue list;
  init(&list);
  int select = 1;
  ElemType item;
  int index;
  while(select){
    printf("*****************************************
");
    printf("*** [1]   push        [2]  pop        ***
");
    printf("*** [3]   show_list   [4]  length     ***
");
    printf("*** [5]   clear       [6]  destroy    ***
");
    printf("*** [0]   quit                        ***
");
    printf("*****************************************
");
    printf("請選擇:>");
    scanf("%d", &select);
    if(0 == select)
      break;
    switch(select){
    case 1:
      printf("請輸入要插入的資料>
");
      scanf("%d",&item);
      enQueue(&list, item);
      show_list(&list);
      break;
    case 2:
      deQueue(&list);
      show_list(&list);
      break;
    case 3:
      show_list(&list);
      break;
    case 5:
      clear(&list);
      show_list(&list);
      break;
    case 6:
      destroy(&list);
      break;
    default:
      printf("輸入的選擇錯誤,請重新選擇
");
      break;
    }
  }
  //destroy(&list);                                                             
}

相關文章