单链表插入删除和访问元素代码c++
时间: 2024-02-19 13:59:13 浏览: 66
单链表插入和删除
5星 · 资源好评率100%
以下是单链表的插入、删除和访问元素的 C++ 代码:
```c++
#include <iostream>
using namespace std;
// 定义链表节点
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 插入节点
void insertNode(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 deleteNode(ListNode *&head, int val) {
if (head == NULL) {
return;
}
if (head->val == val) {
ListNode *tmp = head;
head = head->next;
delete tmp;
} else {
ListNode *cur = head;
while (cur->next != NULL && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != NULL) {
ListNode *tmp = cur->next;
cur->next = tmp->next;
delete tmp;
}
}
}
// 访问节点
int getVal(ListNode *head, int index) {
if (head == NULL) {
return -1;
}
ListNode *cur = head;
while (index > 0 && cur->next != NULL) {
cur = cur->next;
index--;
}
if (index == 0) {
return cur->val;
} else {
return -1;
}
}
int main() {
ListNode *head = NULL;
// 插入节点
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
insertNode(head, 4);
insertNode(head, 5);
// 删除节点
deleteNode(head, 3);
deleteNode(head, 5);
// 访问节点
cout << getVal(head, 0) << endl; // 输出 1
cout << getVal(head, 1) << endl; // 输出 2
cout << getVal(head, 2) << endl; // 输出 4
return 0;
}
```
阅读全文