005 隊列的鏈式存儲

隊列-鏈式結構存儲

#include<iostream>
using namespace std;

typedef int elemtype;

typedef struct LinkNode {
    elemtype data;
    struct LinkNode *next;
}LinkNode;

typedef struct {
    LinkNode *front, *rear;
}LinkQueue;

//初始化隊列,首尾指針全部置空
void InitQueue(LinkQueue &q)
{
    q.front = q.rear = new LinkNode;
    q.front->next = NULL;
}

//隊列判空
bool IsEmpty(LinkQueue &q)
{
    if (q.front == q.rear)
    {
        cout << "It is empty !!" << endl;
        return true;
    }
    else {
        cout << "Not Empty !" << endl;
        return false;
    }

}

//入隊
bool EnQueue(LinkQueue &q, elemtype x)
{
    LinkNode *s = new LinkNode; //s是一個新的結點
    s->data = x;
    s->next = NULL;
    q.rear->next = s;
    q.rear = s;
    return true;
}


//出隊
elemtype DeQueue(LinkQueue &q)
{
    if (q.front == q.rear)  //空隊列
        return false;
    LinkNode * temp = new LinkNode;
    temp = q.front->next;  //temp 就是第一個元素
    elemtype x = temp->data;
    q.front->next = temp->next; //頭指針指向第二個元素
    if (temp == q.rear)    //原來只有一個元素,刪除之後成了空隊
        q.rear = q.front;
    return x;
}
int main()
{
    int aa[5] = { 45,2,3,4,5 };
    LinkQueue q;
    InitQueue(q);
    IsEmpty(q);
    for (int j = 0; j < (sizeof(aa) / sizeof(aa[0])); j++)
    {
        EnQueue(q, aa[j]);
    }
    IsEmpty(q);
    for (int k = 0; k < 5; k++)
    {
        cout << DeQueue(q) << endl;
    }
    IsEmpty(q);
    system("pause");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章