写一个c++程序分别实现顺序栈、链栈的各种基本运算
时间: 2024-11-24 22:41:44 浏览: 23
在C++中,我们可以使用数组来实现顺序栈,而使用链表来实现链栈。以下是简单的顺序栈和链栈的基本操作:
顺序栈(Array Stack)实现:
#include <iostream>
using namespace std;
#define MAX_SIZE 100
class SequenceStack {
private:
int top;
int data[MAX_SIZE];
public:
SequenceStack() : 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++;
data[top] = value;
}
int pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return -1;
}
int poppedValue = data[top];
top--;
return poppedValue;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return data[top];
}
};
int main() {
SequenceStack stack;
// 使用stack进行push, pop, peek等操作...
return 0;
}
链栈(Linked Stack)实现:
#include <iostream>
struct Node {
int value;
Node* next;
Node(int val) : value(val), next(nullptr) {}
};
class LinkedStack {
private:
Node* top;
public:
LinkedStack() : top(nullptr) {}
bool isEmpty() { return top == nullptr; }
void push(int value) {
Node* newNode = new Node(value);
newNode->next = top;
top = newNode;
}
int pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return -1;
}
Node* poppedNode = top;
top = top->next;
delete poppedNode;
return poppedNode->value;
}
int peek() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
return -1;
}
return top->value;
}
};
int main() {
LinkedStack linkedStack;
// 使用linkedStack进行push, pop, peek等操作...
return 0;
}
相关推荐


















