鏈隊列的初始化,建立,插入,查找,刪除。

參考:http://www.cnblogs.com/newwy/archive/2010/10/10/1847463.html
代碼

 

////////////////////////////////////////////
//鏈隊列的初始化,建立,插入,查找,刪除。//
//Author:Wang Yong                            //    
//Date:    2010.8.19                            //
////////////////////////////////////////////



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

typedef int ElemType;

//////////////////////////////////////////

//定義隊列結點類型

typedef struct Qnode
{
    ElemType data;
    struct Qnode *next;
} Qnode;

///定義隊列結點的頭指針,爲指針 

typedef struct
{
    Qnode *front;
    Qnode *rear;
}LQueue,*LinkQueue; 

//////////////////////////////////////////

//隊列初始化

LinkQueue LinkQueueInit()
{
    LinkQueue Q;
    Qnode *P;
    Q = (LinkQueue)malloc(sizeof(LQueue));//申請頭,尾指針結點 
    P = (Qnode *)malloc(sizeof(Qnode));//申請頭結點 
    P->next = NULL;
    Q->front = Q->rear = P;
    return Q; 
}

/////////////////////////////////////////

//入隊

void LinkQueueEnter(LinkQueue Q,ElemType x)
{
    Qnode *p;
    
    p = (Qnode *)malloc(sizeof(Qnode));//申請新結點 
    p->data = x;
    p->next = NULL;

    Q->rear->next = p;
    
    Q->rear = p;

} 

/////////////////////////////////////////

//出隊

ElemType LinkQueueOut(LinkQueue Q)
{
    ElemType x;
    Qnode *p;
    if(Q->front != Q->rear)
    {
        p = Q->front->next;;
        x = p->data;
        Q->front->next = p->next;//移動頭指針 
        free(p);
        if(Q->front->next == NULL)//最後一個元素出隊後,隊空,修改隊尾指針 
            Q->rear = Q->front;
    }
    else 
        return  0;
    return x;
} 
int main()
{
    LinkQueue lqueue;
    lqueue = LinkQueueInit();
    ElemType x;
    printf("請輸入入隊列的元素:");
    while(scanf("%d",&x) != EOF)
    {
        LinkQueueEnter(lqueue,x);
    }
    Qnode *p;
    
    for(p = lqueue->front->next; p != lqueue->rear->next; p = p->next )
        printf("%d ",p->data);
    printf("出隊列的結果爲:");
    while(lqueue->front!= lqueue->rear)
    {
        
        printf("%d ",LinkQueueOut(lqueue));
    }
    
    return 0;
}

發佈了7 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章