
#include
#include
#include
using namespace std;
//队列:先进先出
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next() {}
};
class MyQueue {
private:
ListNode *head;
ListNode *tail;
int _size;
public:
MyQueue() {
head = NULL;
tail = NULL;
_size = 0;
}
bool isEmpty() {
return _size == 0;
}
int size() {
return _size;
}
void push(int value) {
ListNode *cur = new ListNode(value);
if (tail == NULL) {
head = cur;
tail = cur;
} else {
tail->next = cur;
tail = cur;
}
_size++;
}
int pop() {
int ans;
if (head != NULL) {
ListNode *node = head;
ans = head->val;
head = head->next;
free(node);
_size--;
}
if (head == NULL) {
tail = NULL;
}
return ans;
}
int top() {
int ans;
if (head != NULL) {
ans = head->val;
}
return ans;
}
};
void testQueue() {
int testTime = 5000000;
int maxValue = 200000000;
MyQueue *myQueue = new MyQueue();
queue<int> test;
srand(time(0));
cout << "测试开始:" << endl;
for (int i = 0; i < testTime; i++) {
if (myQueue->isEmpty() != test.empty()) {
cout << "Oops! isEmpty() function is wrong!" << endl;
break;
}
if (myQueue->size() != test.size()) {
cout << "size() function is wrong!" << endl;
break;
}
double decide = (rand() % 101) / (double)101;
if (decide < 0.33) {
int num = rand() % maxValue;
myQueue->push(num);
test.push(num);
} else if (decide < 0.66) {
if (!myQueue->isEmpty()) {
int num1 = myQueue->pop();
int num2 = test.front();
test.pop();
if (num1 != num2) {
cout << "pop() function is wrong!" << endl;
break;
}
}
} else {
if (!myQueue->isEmpty()) {
int num1 = myQueue->top();
int num2 = test.front();
if (num1 != num2) {
cout << "top() function is wrong!" << endl;
break;
}
}
}
}
if (myQueue->size() != test.size()) {
cout << "size() function is wrong2!" << endl;
}
while (!myQueue->isEmpty()) {
int num1 = myQueue->pop();
int num2 = test.front();
test.pop();
if (num1 != num2) {
cout << "Oops! pop() function is wrong!" << endl;
break;
}
}
cout << "测试结束!" << endl;
}
int main() {
testQueue();
return 0;
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)