设计单链表表示的整形栈类,要求栈类具有与STL stack类似的接口和功能,并具有拷贝构造、复制赋值、移动构造和移动赋值功能。编写测试程序
时间: 2023-06-02 21:06:05 浏览: 38
好的,了解了您的要求后,我可以为您提供设计单链表表示的整形栈类的代码以及测试程序。以下是代码:
```
#include <iostream>
using namespace std;
// 定义节点类
class Node {
public:
int val;
Node *next;
Node(int x) : val(x), next(NULL) {}
};
// 定义整形栈类
class IntStack {
public:
IntStack() : head(NULL), size(0) {}
IntStack(const IntStack& other) : head(NULL), size(0) {
// 拷贝构造函数
Node *p = other.head;
while (p) {
push(p->val);
p = p->next;
}
}
IntStack& operator=(const IntStack& other) {
// 复制赋值函数
if (this != &other) {
clear();
Node *p = other.head;
while (p) {
push(p->val);
p = p->next;
}
}
return *this;
}
IntStack(IntStack&& other) : head(NULL), size(0) {
// 移动构造函数
head = other.head;
size = other.size;
other.head = NULL;
other.size = 0;
}
IntStack& operator=(IntStack&& other) {
// 移动赋值函数
if (this != &other) {
clear();
head = other.head;
size = other.size;
other.head = NULL;
other.size = 0;
}
return *this;
}
~IntStack() {
clear();
}
void push(int x) {
Node *p = new Node(x);
p->next = head;
head = p;
size++;
}
void pop() {
if (size == 0) {
return;
}
Node *p = head;
head = head->next;
delete p;
size--;
}
int top() {
if (size == 0) {
return -1;
}
return head->val;
}
bool empty() {
return size == 0;
}
void clear() {
while (head) {
Node *p = head;
head = head->next;
delete p;
}
size = 0;
}
private:
Node *head;
int size;
};
// 测试程序
int main() {
IntStack s;
for (int i = 1; i <= 5; i++) {
s.push(i);
}
cout << "top: " << s.top() << endl; // top: 5
s.pop();
cout << "top: " << s.top() << endl; // top: 4
IntStack t = s;
while (!t.empty()) {
cout << t.top() << " ";
t.pop();
}
cout << endl; // 4 3 2 1
IntStack u;
u = move(s);
cout << "empty: " << s.empty() << endl; // empty: 1
cout << "empty: " << u.empty() << endl; // empty: 0
return 0;
}
```
注意:此代码仅供参考,具体实现方法可以根据需求进行修改。