c語言數據結構學習心得——隊列


隊列

只允許在一端進行插入,在另一端進行刪除的線性表

隊頭(Front):允許刪除的一端(隊首)

隊尾(Rear):允許插入的一端

FIFO:先進先出

    不要求從數組首位開始存儲隊列

#define MaxSize 50            //定義隊列中元素的最大個數
typedef struct{
    ElemType data[MaxSize];  //存放隊列元素
    int front,rear;          //隊頭指針和隊尾指針
}SqQueue;

循環隊列

其中,首尾相連的順序存儲的隊列叫循環隊列

入隊:rear=(rear+1)%MaxSize

出隊:front=(front+1)%MaxSize

隊空:front=rear

隊滿:數組中仍有一個空余單元

隊滿時:(rear-front+MaxSize)%MaxSize

1.入隊

bool EnQueue(SqQueue &Q,ElemType x){
    if((Q.rear+1)%MaxSize==Q.front) return false;//隊滿
    Q.data[Q.rear]=x;
    Q.rear=(Q.rear+1)%MaxSize;
    return true;
}

2.出隊

bool DeQueue(SqQueue &Q,ElemType &x){
    if(Q.rear==Q.front) return false;//隊滿
    x=Q.data[Q.front];
    Q.rear=(Q.front+1)%MaxSize;
    return true;
}

 

鏈式隊列

typedef struct{  //鏈式隊列結點
    ElemType data;  
    struct Link Node *next;  
}Link Node;

typedef struct{  //鏈式隊列
    ElemType data;  
    Link Node *front,*rear;//隊頭和隊尾指針 }Link Queue;
 

1.入隊

void EnQueue(LinkQueue &Q,ElemType x){
    s=(LinkNode *)malloc(sizeof(LinkNode));
    s->data=x;
    s->next=NULL;
    Q.rear->next=s;
    Q.rear=s;
}

2.出隊

bool DeQueue(LinkQueue &Q,ElemType &x){
   if(Q.front==Q.rear) return false;   //空隊
   p=Q.front->next;
   x=p->data;
   Q.front->next=p->next;
   if(Q.rear==p) Q.rear=Q.front;       //原隊列只有一個結點刪后變空隊
   free(p);
   return true;
}

 

雙端隊列

具體見上傳圖片

 

總結


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM