链队列的基本实现(C++)
作者:
3include
,
2024-08-05 20:55:24
,
所有人可见
,
阅读 2
#include <iostream>
using namespace std;
struct Node {
int val;
Node *next;
Node(int x): val(x), next(NULL){}
};
struct Queue {
Node *front;
Node *rear;
Queue() {
front = rear = new Node(-1);
}
};
bool isEmpty(Queue *q) {
return q->front->next == NULL;
}
void join(Queue *q, int x) {
Node *node = new Node(x);
q->rear->next = node;
q->rear = node;
}
void quit(Queue *q) {
if(!isEmpty(q)) {
Node *p = q->front->next;
q->front->next = p->next;
if(q->rear == p)
q->rear = q->front;
delete p;
}
}
void print(Queue *q) {
while(!isEmpty(q)) {
cout << q->front->next->val << " ";
quit(q);
}
cout << endl;
}
int main() {
Queue *q = new Queue();
join(q, 1);
join(q, 2);
join(q, 3);
print(q);
return 0;
}