鏈式隊列(Linked Queue)

鏈式隊列


隊列可以使用鏈表的形式來實現。相對於數組來說,使用鏈式存儲結構來實現隊列,在內存空間上沒有數組的限制。

鏈式存儲結構允許在入隊或者出隊時動態的分配內存,因此不會造成內存浪費或者超過限制內存的說法。

隊列的創建


  1. 導入所需頭文件
  2. 定義存儲元素的數據結構Node包含兩個成員data和next
  3. 定義兩個指向數據節點的指針,並且置空(front=rae=NULL)

入隊


  1. 創建一個newNode並給定一個值newNode->next=NULL
  2. 檢查隊列是否爲空(rear==NULL)
  3. 如果爲空,front=newNode和rear=newNode
  4. 如果不爲空,設置rear->next=newNode和rear=newNode
void enQueue(int value){
    struct Node *newNode;
    newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->data=value;
    newNode->next=NULL;
    if (front==NULL){
        front=rear=newNode;
    }else{
        rear->next=newNode;
        rear=newNode;
    }
    printf("插入成功");
}

出隊


  1. 創建一個newNode並給定值,然後newNode->next=NULL
  2. 檢查隊列是否爲空(raer==NULL),終止並關閉
  3. 定義一個指針節點爲temp=front
  4. 設置front=front->next,並釋放temp,free(temp)
void dqQueue(){
    if (front==NULL){
        printf("下溢,隊列爲空");
    }else{
        struct Node *temp=front;
        front=front->next;
        printf("刪除元素: %d \n",temp->data);
        free(temp);
    }
}

完整代碼

struct Node{
    int data;
    struct Node *next;
} *front=NULL,*rear=NULL;

void enQueue(int value){
    struct Node *newNode;
    newNode=(struct Node*)malloc(sizeof(struct Node));
    newNode->data=value;
    newNode->next=NULL:
    if (front==NULL){
        front=raer=newNOde;
    }else{
        rear->next=newNode;
        rear=newNode;
    }
    printf("插入成功\n");
}

void deQueue(){
    if (front==NULL){
        printf("下溢,隊列爲空\n");
    }else{
        struct Node *temp=front;
        front=front->next;
        printf("刪除元素:%d\n",temp->data);
        free(temp);
    }
}
void display(){
    if (front==NULL){
        printf("隊列爲空\n");
    }else{
        struct Node *temp=front;
        while(temp->next!=NULL){
            printf("%d--->",temp->data);
            temp=temp->next;
        }
        printf("%d--->NULL\n",temp->data);
    }
}
void main(){
    int choice,value;
    while(1){
        printf("鏈隊");
        printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
        printf("輸入你的選擇");
        scanf("%d",&chioce);

        switch(chiose){
            case 1:
                printf("輸入值被插入隊列");
                scanf("%d",&value);
                enQueue(value);
                break;
            case 2:
                deQueue();
                break;
            case 3:
                display();
                break;
            case 4:
                exit(0);
            default:
            printf("輸入錯誤,請重試");

        }
    }
}

更多內瓤,歡迎關注:


在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章