c++实现链表的插入和删除
时间: 2023-09-25 12:12:58 浏览: 112
链表是一种常见的数据结构,它可以用来存储一系列的数据,并且支持动态的插入和删除操作。下面是C++实现链表的插入和删除操作的示例代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
public:
LinkedList() {
head = nullptr;
}
void insertNode(int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
void deleteNode(int value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* temp = head;
while (temp->next != nullptr && temp->next->data != value) {
temp = temp->next;
}
if (temp->next != nullptr) {
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
}
}
}
void printList() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
private:
Node* head;
};
int main() {
LinkedList myList;
myList.insertNode(1);
myList.insertNode(2);
myList.insertNode(3);
myList.insertNode(4);
myList.insertNode(5);
myList.printList();
myList.deleteNode(3);
myList.deleteNode(1);
myList.printList();
return 0;
}
```
在这个示例代码中,我们定义了一个`LinkedList`类来表示链表。它包含一个`Node`结构体来表示节点,以及一个`head`成员指向链表的第一个节点。在`insertNode`函数中,我们创建一个新的节点,并将其插入到链表的末尾。在`deleteNode`函数中,我们遍历链表,查找要删除的节点,并将其从链表中删除。最后,我们还定义了一个`printList`函数来输出链表中的所有节点。在`main`函数中,我们创建一个`LinkedList`对象,并测试插入和删除操作的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)