1. 程式人生 > 其它 >線性結構之順序隊

線性結構之順序隊

佇列,是隻能通過訪問它的一端來實現資料儲存和檢索的一種線性資料結構。對於佇列的修改要按照先進先出的原則進行,因此,佇列又被稱為先進先出(FIFO)的線性表。

順序隊,佇列的順序結構。

基本方法有:

  1. 初始化:建立一個空的佇列。
  2. 判斷佇列是否為空:如果佇列為空,則返回”真“,否則返回”假“。
  3. 入隊:將元素x加入到佇列的隊尾,並更新隊尾指標。
  4. 出隊:將隊頭元素從佇列中刪除,並更新隊頭指標。
  5. 讀取隊頭元素:返回對頭元素的值,但不更新隊頭指標。

C語言實現

#define TRUE 1
#define FALSE 0
#define ERROR -1
#define NULL -2
typedef 
int bool; typedef int ElementType; typedef int Position; Queue CreateQueue(int MaxSize); bool IsFull(Queue Q); bool IsEmpty(Queue Q); bool AddQ(Queue Q, ElementType X); ElementType DeleteQ(Queue Q); struct QNode { ElementType *Data; /* 儲存元素的陣列 */ Position Front, Rear; /* 佇列的頭、尾指標 */ int
MaxSize; /* 佇列最大容量 */ }; typedef struct QNode *Queue; Queue CreateQueue( int MaxSize ) { Queue Q = (Queue)malloc(sizeof(struct QNode)); Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); Q->Front = Q->Rear = 0; Q->MaxSize = MaxSize; return Q; }
bool IsFull( Queue Q ) { return ((Q->Rear+1)%Q->MaxSize == Q->Front); } bool AddQ( Queue Q, ElementType X ) { if ( IsFull(Q) ) { printf("佇列滿"); return FALSE; } else { Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return TRUE; } } bool IsEmpty( Queue Q ) { return (Q->Front == Q->Rear); } ElementType DeleteQ( Queue Q ) { if ( IsEmpty(Q) ) { printf("佇列空"); return ERROR; } else { Q->Front =(Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } }

應用

  1. 排隊買 XXX
  2. 醫院的掛號系統