建立单链表,实现插入元素、删除元素、查询、求表长度的C++代码
时间: 2024-06-17 13:02:35 浏览: 11
建立单链表的C++代码如下:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 插入元素到链表尾部
void insert(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
if (head == NULL) {
head = newNode;
} else {
ListNode* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除指定元素
void remove(ListNode*& head, int val) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy;
while (cur->next != NULL) {
if (cur->next->val == val) {
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
} else {
cur = cur->next;
}
}
head = dummy->next;
delete dummy;
}
// 查询元素是否存在
bool search(ListNode* head, int val) {
ListNode* cur = head;
while (cur != NULL) {
if (cur->val == val) {
return true;
}
cur = cur->next;
}
return false;
}
// 求链表长度
int getLength(ListNode* head) {
int length = 0;
ListNode* cur = head;
while (cur != NULL) {
length++;
cur = cur->next;
}
return length;
}
// 打印链表
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != NULL) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
}
int main() {
ListNode* head = NULL;
// 插入元素
insert(head, 1);
insert(head, 2);
insert(head, 3);
// 打印链表
printList(head);
// 删除元素
remove(head, 2);
// 打印链表
printList(head);
// 查询元素
cout << "是否存在元素3:" << (search(head, 3) ? "是" : "否") << endl;
// 求链表长度
cout << "链表长度:" << getLength(head) << endl;
return 0;
}
```
相关推荐
![](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)
![](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)