链表的建立,插入、查询,删除等操作的代码
时间: 2024-04-30 07:17:45 浏览: 11
好的,以下是链表的建立、插入、查询和删除等操作的示例代码:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 创建链表
ListNode* createList() {
ListNode* head = new ListNode(0); // 创建头结点
ListNode* p = head;
int x;
cout << "请输入链表元素(输入-1结束):" << endl;
cin >> x;
while (x != -1) {
ListNode* node = new ListNode(x);
p->next = node;
p = node;
cin >> x;
}
return head->next;
}
// 遍历链表
void printList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
cout << p->val << " ";
p = p->next;
}
cout << endl;
}
// 插入节点
void insertNode(ListNode* head, int pos, int val) {
ListNode* p = head;
for (int i = 0; i < pos - 1; i++) {
if (p == NULL) {
cout << "插入位置不合法!" << endl;
return;
}
p = p->next;
}
ListNode* node = new ListNode(val);
node->next = p->next;
p->next = node;
}
// 查询节点
ListNode* searchNode(ListNode* head, int val) {
ListNode* p = head;
while (p != NULL) {
if (p->val == val) {
return p;
}
p = p->next;
}
return NULL;
}
// 删除节点
void deleteNode(ListNode* head, int val) {
ListNode* p = head;
ListNode* pre = NULL;
while (p != NULL) {
if (p->val == val) {
if (pre == NULL) { // 删除头结点
head = p->next;
} else {
pre->next = p->next;
}
delete p;
return;
}
pre = p;
p = p->next;
}
cout << "链表中不存在该元素!" << endl;
}
int main() {
ListNode* head = createList();
printList(head);
insertNode(head, 3, 5);
printList(head);
ListNode* node = searchNode(head, 2);
if (node != NULL) {
cout << "查询到元素:" << node->val << endl;
} else {
cout << "链表中不存在该元素!" << endl;
}
deleteNode(head, 4);
printList(head);
return 0;
}
```
这段代码可以创建链表、打印链表、在指定位置插入节点、查询链表中是否存在某个值的节点以及删除链表中某个节点。
相关推荐
![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_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)