链式队列的基本操作代码c++
时间: 2023-10-18 19:22:10 浏览: 98
链式队列的基本操作包括:初始化队列、判断队列是否为空、入队、出队、获取队头元素等。下面是链式队列的基本操作代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class Queue {
private:
Node* front;
Node* rear;
public:
Queue() {
front = NULL;
rear = NULL;
}
bool isEmpty() {
return (front == NULL);
}
void enqueue(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = NULL;
if (isEmpty()) {
front = newNode;
rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
void dequeue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
} else {
Node* temp = front;
front = front->next;
cout << "Dequeued value: " << temp->data << endl;
delete temp;
}
}
int getFront() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return -1;
} else {
return front->data;
}
}
void display() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
} else {
Node* temp = front;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
};
int main() {
Queue q;
q.dequeue();
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.display();
q.dequeue();
q.dequeue();
cout << "Front element: " << q.getFront() << endl;
q.display();
return 0;
}
```
以上代码实现了链式队列的基本操作,可以通过调用enqueue方法来添加元素,调用dequeue方法来移出元素,调用getFront方法来获取队头元素,调用display方法来显示队列中所有元素。
阅读全文