用C++写出建立链表,和链表的插入,删除
时间: 2023-05-13 19:07:31 浏览: 69
链表是一种常见的数据结构,用于存储一系列的元素。下面是用 C++ 实现链表的代码:
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class LinkedList {
public:
LinkedList() {
head = NULL;
}
void insert(int val) {
ListNode* node = new ListNode(val);
if (head == NULL) {
head = node;
} else {
ListNode* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
}
void remove(int val) {
if (head == NULL) {
return;
}
if (head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
return;
}
ListNode* cur = head;
while (cur->next != NULL && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != NULL) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
}
void print() {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
ListNode* head;
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.print();
list.remove(2);
list.print();
return 0;
}
```
这段代码实现了链表的建立、插入和删除操作。其中,`ListNode` 结构体表示链表中的一个节点,包含一个整数值和一个指向下一个节点的指针。`LinkedList` 类表示链表,包含一个指向链表头节点的指针。`insert` 方法用于在链表末尾插入一个节点,`remove` 方法用于删除链表中指定值的节点,`print` 方法用于打印链表中的所有节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_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)