数据结构实现链表基本操作,并用rand函数测试每个函数的运行时间
时间: 2023-12-06 18:02:57 浏览: 75
好的,以下是用C++实现链表基本操作,并用rand函数测试每个函数的运行时间的代码:
```c++
#include <iostream>
#include <ctime>
using namespace std;
struct Node {
int val;
Node *next;
Node(int x) : val(x), next(NULL) {}
};
class LinkedList {
public:
LinkedList() {
head = NULL;
}
void addAtHead(int val) {
Node *newNode = new Node(val);
newNode->next = head;
head = newNode;
}
void addAtTail(int val) {
if (head == NULL) {
addAtHead(val);
return;
}
Node *cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new Node(val);
}
void addAtIndex(int index, int val) {
if (index == 0) {
addAtHead(val);
return;
}
int i = 0;
Node *cur = head;
while (cur != NULL && i < index - 1) {
cur = cur->next;
i++;
}
if (cur == NULL) {
return;
}
Node *newNode = new Node(val);
newNode->next = cur->next;
cur->next = newNode;
}
void deleteAtIndex(int index) {
if (head == NULL) {
return;
}
if (index == 0) {
Node *temp = head;
head = head->next;
delete temp;
return;
}
int i = 0;
Node *cur = head;
while (cur != NULL && i < index - 1) {
cur = cur->next;
i++;
}
if (cur == NULL || cur->next == NULL) {
return;
}
Node *temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
void printList() {
Node *cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
Node *head;
};
int main() {
LinkedList list;
srand(time(NULL)); // 初始化rand函数
// 随机生成1000个数,插入链表并打印链表
clock_t start = clock();
for (int i = 0; i < 1000; i++) {
int val = rand() % 100;
list.addAtTail(val);
}
list.printList();
clock_t end = clock();
cout << "Time used: " << end - start << endl;
// 在第500个位置插入一个数,并打印链表
start = clock();
list.addAtIndex(500, 999);
list.printList();
end = clock();
cout << "Time used: " << end - start << endl;
// 删除第500个数,并打印链表
start = clock();
list.deleteAtIndex(500);
list.printList();
end = clock();
cout << "Time used: " << end - start << endl;
return 0;
}
```
上面的代码中,我们用rand函数随机生成了1000个数,插入链表中,并打印了链表。然后在第500个位置插入了一个数,并打印了链表。最后删除了第500个数,并打印了链表。每个操作都用clock函数计算了运行时间。
需要注意的是,这里使用了rand函数生成随机数,所以每次运行结果可能会不同。
阅读全文