数据结构与算法用visual studio2022写一个建立链表指定位置插入删除与按位置查找的源文件与头文件
时间: 2024-10-28 16:10:12 浏览: 24
在Visual Studio 2022中,我们可以使用C++来创建一个简单的链表数据结构,并实现插入、删除和查找功能。这里是一个基础的链表实现示例,包括头文件`LinkedList.h`和源文件`LinkedList.cpp`。
**LinkedList.h**
```cpp
#pragma once
#include <iostream>
class Node {
public:
int data;
Node* next;
Node(int value = 0) : data(value), next(nullptr) {}
};
class LinkedList {
private:
Node* head;
public:
LinkedList();
~LinkedList();
void insert(int index, int value);
void remove(int index);
int find(int value);
void display() const;
};
```
**LinkedList.cpp**
```cpp
#include "LinkedList.h"
LinkedList::LinkedList() : head(nullptr) {}
LinkedList::~LinkedList() {
Node* current = head;
while (current) {
Node* temp = current;
current = current->next;
delete temp;
}
}
void LinkedList::insert(int index, int value) {
if (index <= 0) {
insertAtHead(value);
return;
}
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
return;
}
Node* prev = head;
for (int i = 0; i < index - 1 && prev->next != nullptr; ++i) {
prev = prev->next;
}
if (prev == nullptr) {
std::cout << "Invalid index\n";
return;
}
newNode->next = prev->next;
prev->next = newNode;
}
void LinkedList::remove(int index) {
if (head == nullptr || index <= 0) {
std::cout << "Invalid index\n";
return;
}
if (index == 1) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
for (int i = 0; i < index - 1; ++i) {
current = current->next;
}
if (current->next == nullptr) {
std::cout << "Node at the given index not found.\n";
return;
}
current->next = current->next->next;
}
int LinkedList::find(int value) {
Node* current = head;
int position = 1;
while (current != nullptr && current->data != value) {
current = current->next;
position++;
}
return current ? position : -1; // 找不到返回-1
}
void LinkedList::display() const {
if (head == nullptr) {
std::cout << "Empty list.\n";
return;
}
Node* temp = head;
while (temp) {
std::cout << temp->data << " -> ";
temp = temp->next;
}
std::cout << "NULL" << std::endl;
}
```
你可以将这两个文件分别命名为`LinkedList.h`和`LinkedList.cpp`,并在Visual Studio 2022中打开它们进行编辑。然后在需要使用链表的地方,`#include "LinkedList.h"`导入这个头文件即可。
阅读全文