C++:编写一个程序实顺序栈的各种基本运算;实现队列的链式表示和实现
时间: 2024-11-30 08:14:47 浏览: 33
在C++中,我们可以使用结构体或类来实现顺序栈和队列的数据结构。这里我会提供一些基础的实现思路:
**顺序栈(基于数组实现)**:
```cpp
#include <iostream>
// 定义栈结构体
template <typename T>
class Stack {
private:
T* arr; // 数组元素
size_t top; // 栈顶指针
public:
Stack(size_t capacity) : arr(new T[capacity]), top(0) {}
// 入栈操作 (push)
void push(const T& item) {
if (top == capacity) {
std::cout << "Stack overflow" << std::endl;
return;
}
arr[top++] = item;
}
// 出栈操作 (pop)
bool pop(T& item) {
if (top == 0) {
std::cout << "Stack underflow" << std::endl;
return false;
}
item = arr[--top];
return true;
}
// 查看栈顶元素 (peek)
bool peek(T& item) const {
if (top == 0) {
std::cout << "Stack is empty" << std::endl;
return false;
}
item = arr[top - 1];
return true;
}
// 判断栈是否为空
bool isEmpty() const {
return top == 0;
}
~Stack() { delete[] arr; } // 析构函数释放内存
};
int main() {
Stack<int> s(5);
s.push(1);
s.push(2);
s.pop(); // 输出1
return 0;
}
```
**链式队列(基于节点)**:
```cpp
#include <iostream>
// 定义队列节点
struct Node {
T data;
Node* next;
};
template <typename T>
class Queue {
private:
Node* front; // 队首指针
Node* rear; // 队尾指针
public:
Queue() : front(nullptr), rear(nullptr) {}
// 入队 (enqueue)
void enqueue(const T& item) {
Node* newNode = new Node{item, nullptr};
if (rear == nullptr) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
// 出队 (dequeue)
bool dequeue(T& item) {
if (front == nullptr) {
std::cout << "Queue is empty" << std::endl;
return false;
}
item = front->data;
Node* temp = front;
front = front->next;
if (front == nullptr) {
rear = nullptr;
}
delete temp;
return true;
}
// 查看队头元素 (peek)
bool peek(T& item) const {
if (front == nullptr) {
std::cout << "Queue is empty" << std::endl;
return false;
}
item = front->data;
return true;
}
// 检查队列是否为空
bool isEmpty() const {
return front == nullptr;
}
~Queue() {
Node* current = front;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
};
int main() {
Queue<int> q;
q.enqueue(1);
q.enqueue(2);
q.dequeue(); // 输出1
return 0;
}
```
阅读全文