1.顺序表
#include <iostream>
using namespace std;
template <typename T>
class ArrayList {
private:
T* data;
int size;
int capacity;
void resize(int newCapacity) {
T* newData = new T[newCapacity];
for (int i = 0; i < size; ++i) {
newData[i] = data[i];
}
delete[] data;
data = newData;
capacity = newCapacity;
}
public:
ArrayList(int cap = 10) : size(0), capacity(cap) {
data = new T[capacity];
}
~ArrayList() {
delete[] data;
}
void add(const T& item) {
if (size == capacity) {
resize(capacity * 2);
}
data[size++] = item;
}
T get(int index) const {
if (index >= 0 && index < size) {
return data[index];
}
throw out_of_range("Index out of range");
}
void set(int index, const T& item) {
if (index >= 0 && index < size) {
data[index] = item;
} else {
throw out_of_range("Index out of range");
}
}
int getSize() const {
return size;
}
};
2.栈
#include <iostream>
using namespace std;
template <typename T>
class Stack {
private:
T* data;
int top;
int capacity;
void resize(int newCapacity) {
T* newData = new T[newCapacity];
for (int i = 0; i <= top; ++i) {
newData[i] = data[i];
}
delete[] data;
data = newData;
capacity = newCapacity;
}
public:
Stack(int cap = 10) : top(-1), capacity(cap) {
data = new T[capacity];
}
~Stack() {
delete[] data;
}
void push(const T& item) {
if (top == capacity - 1) {
resize(capacity * 2);
}
data[++top] = item;
}
T pop() {
if (top >= 0) {
return data[top--];
}
throw out_of_range("Stack underflow");
}
T peek() const {
if (top >= 0) {
return data[top];
}
throw out_of_range("Stack underflow");
}
bool isEmpty() const {
return top == -1;
}
};
队列
#include <iostream>
using namespace std;
template <typename T>
class Queue {
private:
T* data;
int front;
int rear;
int size;
int capacity;
void resize(int newCapacity) {
T* newData = new T[newCapacity];
for (int i = 0; i < size; ++i) {
newData[i] = data[(front + i) % capacity];
}
front = 0;
rear = size;
delete[] data;
data = newData;
capacity = newCapacity;
}
public:
Queue(int cap = 10) : front(0), rear(0), size(0), capacity(cap) {
data = new T[capacity];
}
~Queue() {
delete[] data;
}
void enqueue(const T& item) {
if (size == capacity) {
resize(capacity * 2);
}
data[rear] = item;
rear = (rear + 1) % capacity;
++size;
}
T dequeue() {
if (size > 0) {
T item = data[front];
front = (front + 1) % capacity;
--size;
return item;
}
throw out_of_range("Queue underflow");
}
bool isEmpty() const {
return size == 0;
}
};