用c++写一段代码 在两种存储结构上能够实现栈和队列的基本运算,特别注意栈满、栈空、队满、队空
时间: 2024-10-16 11:14:23 浏览: 33
在C++中,我们可以分别使用数组和链表这两种数据结构来实现栈和队列。这里我将给出简单的示例代码:
### 使用数组实现栈(ArrayStack):
```cpp
#include <iostream>
using namespace std;
#define MAX_SIZE 100
class ArrayStack {
private:
int top;
int arr[MAX_SIZE];
public:
ArrayStack() : top(-1) {}
bool isEmpty() { return top == -1; }
bool isFull() { return top == MAX_SIZE - 1; }
void push(int value) {
if (isFull()) {
cout << "Stack Overflow" << endl;
return;
}
top++;
arr[top] = value;
}
int pop() {
if (isEmpty()) {
cout << "Stack Underflow" << endl;
return -1;
}
int poppedValue = arr[top];
top--;
return poppedValue;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return -1;
}
return arr[top];
}
};
// 示例
int main() {
ArrayStack stack;
stack.push(1);
stack.push(2);
stack.push(3);
cout << "Top element: " << stack.peek() << endl;
stack.pop();
cout << "After pop: Top element = " << stack.peek() << endl;
return 0;
}
```
### 使用链表实现队列(LinkedListQueue):
```cpp
#include <iostream>
template <typename T>
class Node {
public:
T data;
Node<T>* next;
Node(T val) : data(val), next(nullptr) {}
};
template <typename T>
class LinkedListQueue {
private:
Node<T>* front, *rear;
public:
LinkedListQueue() : front(nullptr), rear(nullptr) {}
bool isEmpty() { return front == nullptr; }
bool isFull() { return false; } // 链表队列无容量限制
void enqueue(T value) {
Node<T>* newNode = new Node<T>(value);
if (isEmpty()) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
}
T dequeue() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return T(); // 返回默认值或抛异常
}
T removedValue = front->data;
Node<T>* temp = front;
front = front->next;
delete temp;
return removedValue;
}
T front() {
if (isEmpty()) {
cout << "Queue is empty" << endl;
return T(); // 返回默认值或抛异常
}
return front->data;
}
};
// 示例
int main() {
LinkedListQueue<int> queue;
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
cout << "Front element: " << queue.front() << endl;
queue.dequeue();
cout << "After dequeue: Front element = " << queue.front() << endl;
return 0;
}
```
以上代码展示了如何使用数组实现固定大小的栈,以及如何使用链表实现动态大小的队列。需要注意的是,在实际应用中,处理队空和栈空的情况需要考虑到边界条件和错误处理。
阅读全文