編程實現隊列的入隊/出隊操作


思路:隊列其實也是一個鏈表,只是隊列還有兩個特殊的結點,一個指向隊頭,一個指向隊尾。先設計數據結構,如下

typedef struct student * PNode;
typedef struct linkqueue * Pqueue;

typedef struct student
{
    int data;
    PNode next;
}Node;


typedef struct linkqueue
{
    PNode first;
    PNode rear;
}queue;

1.入隊操作其實是指向隊尾的指針向后移,要判斷隊列是否為空或者只有一個結點的情況

2.出隊操作其實是指向隊頭的指針向后移

整體代碼如下:

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

typedef struct student * PNode;
typedef struct linkqueue * Pqueue;

typedef struct student
{
    int data;
    PNode next;
}Node;


typedef struct linkqueue
{
    PNode first;
    PNode rear;
}queue;


Pqueue insert(Pqueue link,int num)
{
    PNode p;
    Pqueue q=link;
        p=(PNode)malloc(sizeof(Node));
        p->data=num;
    if(link==NULL)
    {
        printf("添加第一個結點\n");
        q=(Pqueue)malloc(sizeof(queue));
        q->first=p;
        q->rear=p;
        q->rear->next=NULL;
        return q;
    }
    q->rear->next=p;
    q->rear=p;    
    q->rear->next=NULL;
    return q;
}

Pqueue del(Pqueue queue)
{
    if(queue==NULL)
    {
        printf("隊列為空");
        return NULL;
    }
    Pqueue q=queue;
    PNode temp;
    temp=q->first;
    if(q->first->next!=NULL)
        q->first=q->first->next;
    else
    {
        printf("隊列只有一個結點,刪除完畢\n");
        return NULL;
    }
    free(temp);
    return q;
}

void print(Pqueue link)
{
    PNode q=link->first;
    while(q!=NULL)
    {
        printf("%d ",q->data);
        q=q->next;
    }
    printf("\n");
}

int main(void)
{
    Pqueue linkqueue=NULL;
    int flag=0,num;
    while(1)
    {
        printf("選擇入隊或者出隊:1為入隊,2為出隊,0為退出\n");
        scanf("%d",&flag);
        if(flag==1)
        {
            printf("請選擇要入隊的值:\n");
            scanf("%d",&num);
            linkqueue=insert(linkqueue,num);
            printf("打印入隊后的隊列:\n");
            print(linkqueue);
        }
        else if(flag==2)
        {
            linkqueue=del(linkqueue);
            printf("打印出隊后的隊列:\n");
            print(linkqueue);
        }
        else
            break;
    }
    printf("打印最后的隊列:\n");
    print(linkqueue);
    return 0;
}

 程序猿必讀


免責聲明!

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



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