设计一个算法用VS2015编译器完成单链表的建立、取值、查找、插入和删除操作。单链表存储元素为int的数据元素,取值范围1到900。
时间: 2024-10-08 09:10:50 浏览: 25
RSA算法设计与实现.pdf
在VS2015中,我们可以创建一个简单的单链表数据结构,并提供相应的操作函数。首先,我们需要定义一个Node类表示链表节点,包含一个整数值和指向下一个节点的指针。然后创建LinkedList类,实现链表的基本功能。
```cpp
// Node.h
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// LinkedList.cpp
#include "Node.h"
class LinkedList {
private:
Node* head; // 链表头指针
public:
LinkedList() : head(nullptr) {}
// 插入操作
void insert(int value) {
Node* newNode = new Node(value);
if (!head)
head = newNode;
else
Node* current = head;
while (current->next)
current = current->next;
current->next = newNode;
}
// 查找操作
bool find(int value) {
Node* current = head;
while (current) {
if (current->data == value)
return true;
current = current->next;
}
return false;
}
// 取值操作(返回false表示未找到)
bool getValue(int index, int& result) const {
if (index < 0 || index >= size())
return false;
Node* current = head;
for (int i = 0; i < index; i++)
current = current->next;
result = current->data;
return true;
}
// 删除操作
void remove(int value) {
if (!head) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next && current->next->data != value)
current = current->next;
if (current->next)
current->next = current->next->next;
else
std::cout << "Value not found in the list." << std::endl;
}
// 返回链表长度
int size() const {
int count = 0;
Node* current = head;
while (current)
{
count++;
current = current->next;
}
return count;
}
};
```
阅读全文