模板实现顺序表、栈、队列
#include <iostream>template <typename T>
class SeqList {
private:T* data;int size;int capacity;public:SeqList(int capacity = 10): size(0), capacity(capacity), data(new T[capacity]) {}~SeqList() { delete[] _data; }void PushBack(const T& value) {if (size >= capacity) {Expand();}data[size++] = value;}void PopBack() {if (size > 0) {--size;}}T& operator[](int index) {return data[index];}const T& operator[](int index) const {return data[index];}int Size() const { return size; }bool Empty() const { return size == 0; }private:void Expand() {capacity *= 2;T* newData = new T[capacity];for (int i = 0; i < size; ++i) {newData[i] = data[i];}delete[] data;data = newData;}};int main() {SeqList<int> list;list.PushBack(1);list.PushBack(2);list.PushBack(3);for (int i = 0; i < list.Size(); ++i) {std::cout << list[i] << " ";}return 0;
}
#include <iostream>template <typename T>
class Stack {private:T* data;int size;int capacity;public:Stack(int capacity = 10): size(0), capacity(capacity), data(new T[capacity]) {}~Stack() { delete[] data; }void push(const T& value) {if (size >= capacity) {expand();}data[size++] = value;}void Pop() {if (size > 0) {--size;}}T& Top() {return data[size - 1];}const T& Top() const {return data[size - 1];}int Size() const { return size; }bool empty() const { return size == 0; }private:void expand() {capacity *= 2;T* newData = new T[capacity];for (int i = 0; i < size; ++i) {newData[i] = data[i];}delete[] data;data = newData;}};int main() {Stack<int> s;s.push(10);s.push(20);s.push(30);while (!s.empty()) {std::cout << s.Top() << " ";s.pop();}return 0;
}
#include <iostream>template <typename T>
class Queue {
private:T* data;int front;int rear;int size;int capacity;public:Queue(int capacity = 10): front(0), rear(0), size(0), capacity(capacity), data(new T[capacity]) {}~Queue() { delete[] data; }void push(const T& value) {if (size >= capacity) {expand();}data[rear] = value;rear = (rear + 1) % capacity;++size;}void pop() {if (size > 0) {front = (front + 1) % capacity;--size;}}T& Front() {return data[front];}const T& Front() const {return data[front];}int Size() const { return size; }bool empty() const { return size == 0; }private:void expand() {T* newData = new T[capacity * 2];for (int i = 0; i < size; ++i) {newData[i] = data[(front + i) % capacity];}capacity *= 2;front = 0;rear = size;delete[] data;data = newData;}};int main() {Queue<int> q;q.push(1);q.push(2);q.push(3);while (!q.empty()) {std::cout << q.Front() << " ";q.pop();}return 0;
}