佇列(Queue)

Common operations from the C++ Standard Template Library include the following:

Returns True if the queue is empty, and False otherwise.
front()
Returns a reference to the value at the front of a non-empty queue. There is also a constant version of this function, const T& front().
pop()
Removes the item at the front of a non-empty queue.
push()
Inserts the argument foo at the back of the queue.
size()
Returns the total number of elements in the queue.bool empty()

 

For Example:CPP


#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>

#define MAX 100

char *p[MAX], *pop(void);
int spos = 0;
int rpos = 0;
void add(void), push(char *q), print(void), remove(void);


void add(void)
{
  char s[256], *p;

  do {
    printf("spos %d: ", spos+1);
    gets(s);
    if(*s==0) {
       break;
    }
    p = (char *malloc(strlen(s)+1);
    if(!p) {
      printf("Out of memory.\n");
      return;
    }
    strcpy(p, s);
    if(*s) {
       push(p);
    }
  while(*s);
}

void print(void)
{
  int t;

  for(t=rpos; t < spos; ++t)
    printf("%d. %s\n", t+1, p[t]);
}

void remove(void)
{
  char *p;

  if((p=pop())==NULL) {
     return;
  }
  printf("%s\n", p);
}

void push(char *q)
{
  if(spos==MAX) {
    printf("List Full\n");
    return;
  }
  p[spos= q;
  spos++;
}

char *pop(void)
{
  if(rpos==spos) {
    printf("No more.\n");
    return NULL;
  }
  rpos++;
  return p[rpos-1];
}

int main(void)
{
  char s[80];
  register int t;

  for(t=0; t < MAX; ++t) {
     p[t= NULL;
  }

  while(1) {
    printf("Add(A), Print(P), Remove(R), Quit(Q): ");
    gets(s);
    *s = toupper(*s);

    switch(*s) {
      case 'A':
        add();
        break;
      case 'P':
        print();
        break;
      case 'R':
        remove();
        break;
      case 'Q':
        exit(0);
    }
  }
  return 0;
}

 

For Example2:CPP

#include<stdio.h>
#include<stdlib.h>
/*佇列資料結構*/
struct Queue
{
  int Array[100];//陣列空間大小
  int head;//前端(front)
  int tail;//後端(rear)
  int length;//佇列長度     
};
/*資料加入佇列*/
void EnQueue(Queue *Queue1,int x)
{
  Queue1->Array[Queue1->tail]=x;
  if(Queue1->tail==Queue1->length)
  {
    Queue1->tail=1;                
  }
  else
  {
    Queue1->tail=Queue1->tail+1;
    Queue1->length=Queue1->length+1;//這行邏輯上有問題   //Modify By pcjackal.tw
  }
}
/*資料移出佇列*/
int DeQueue(Queue *Queue1)
{
  int x=Queue1->Array[Queue1->head];
  if(Queue1->head==Queue1->length)
  {
    Queue1->head==1;                               
  }
  else
  {
    Queue1->head=Queue1->head+1;    
  }
  return x;
}
/*佇列操作*/
int main()
{
  struct Queue Queue1;//建立資料結構
  Queue1.length=10;//新增長度
  Queue1.head=0;//必須要先初始化
  Queue1.tail=0;//必須要先初始化
  EnQueue(&Queue1,5);//將5放入佇列
  EnQueue(&Queue1,8);//將8放入佇列
  EnQueue(&Queue1,3);//將3放入佇列
  EnQueue(&Queue1,2);//將2放入佇列
  printf("%d ",DeQueue(&Queue1));//輸出佇列(5)  
  printf("%d ",DeQueue(&Queue1));//輸出佇列(8)
  printf("%d ",DeQueue(&Queue1));//輸出佇列(3) 
  system("pause");   
}