服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++代码实现链队列详解

C++代码实现链队列详解

2022-01-12 14:20果酱包 C/C++

下面小编就为大家分享一篇C++代码实现链队列的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧,希望能够给你带来帮助

主要功能:

初始化入队出队取队头元素销毁队列输出队列

完整代码展示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct QueNode{  //定义链队列存储结构
    int data;
    QueNode * next;
}QNode,*QuePtr;
typedef struct //定义链队列指针
    QuePtr front;  //队头指针
    QuePtr rear;  //队尾指针
}LinkQue;
bool InitQue(LinkQue &Q){  //初始化
    Q.front = Q.rear = new QNode;
    if (!Q.front) return false;
    Q.front->next = NULL;
    return true;
}
bool DestoryQue(LinkQue &Q){  //销毁表
    while (Q.front){
        Q.rear = Q.front->next;
        delete(Q.front);
        Q.front = Q.rear;
    }
    return true;
}
bool EnQue(LinkQue &Q,int e){  //入队
    QuePtr p = new QNode;
    if(!p) return false;
    p->data = e;
    p->next = NULL;
    Q.rear->next = p;
    Q.rear = p;
    return true;
}
bool OutQue(LinkQue &Q,int e){  //出队
    if(Q.front == Q.rear) return false//队空
    QuePtr p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if(Q.rear == p) Q.rear = Q.front;
    delete p;
    return true;
}
bool GetHead(LinkQue Q,int &e){  //取队头元素
    if(Q.front == Q.rear) return false;
    e = Q.front->next->data;
    return true;
}
void ShowList(LinkQue Q){   //输出链队
    QuePtr p = Q.front->next;
    while (p){
        cout<<p->data<<" ";
        p = p->next;
    }
    cout<<endl;
}
int main() {
    LinkQue Q;
    int e;
    int choose = -1;
    cout<<"1.入队-------------------2.出队"<<endl;
    cout<<"3.取头元素---------------4.销毁"<<endl;
    cout<<"5.输出链队---------------0.退出"<<endl;
    InitQue(Q);
    while (choose != 0) {
        cout << "请选择功能:";
        cin >> choose;
        switch (choose) {
            case 1:
                cout << "请输入入队元素:";
                cin >> e;
                if (EnQue(Q, e))
                    cout << "入队成功" << endl;
                break;
            case 2:
                if (OutQue(Q, e))
                    cout << "出队成功" << endl;
                break;
            case 3:
                if (GetHead(Q, e))
                    cout << "队头元素为" << e << endl;
                break;
            case 4:
                if (DestoryQue(Q))
                    cout << "销毁成功" << endl;
                break;
            case 5:
                cout << "队列元素为:";
                ShowList(Q);
                break;
        }
    }
    return 0;
}

运行结果图:

C++代码实现链队列详解

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/qq_46601680/article/details/120498387

延伸 · 阅读

精彩推荐