c++实现单链表,包括单链表的生成,元素插入,删除操作
时间: 2024-09-17 22:09:41 浏览: 46
在C++中,单链表是一种基础的数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。以下是基本的单链表实现步骤:
1. **链表节点定义**:
```cpp
struct ListNode {
int val; // 节点值
ListNode* next; // 指向下一个节点的指针
ListNode(int x) : val(x), next(nullptr) {} // 构造函数,初始化值和next为nullptr
};
```
2. **生成空链表**:
创建一个链表的开始通常是一个空头节点(head),表示链表为空:
```cpp
ListNode* head = nullptr;
```
3. **元素插入**:
- 插入到链表头部:
```cpp
void insertAtHead(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
newNode->next = head;
head = newNode;
}
```
- 插入到指定位置:
```cpp
void insertAtPosition(ListNode*& head, int pos, int val) {
if (pos <= 0 || !head) return;
ListNode* newNode = new ListNode(val);
ListNode* current = head;
for (int i = 0; i < pos - 1 && current != nullptr; ++i)
current = current->next;
if (current == nullptr) return;
newNode->next = current->next;
current->next = newNode;
}
```
4. **元素删除**:
- 删除头部元素:
```cpp
void deleteFromHead(ListNode*& head) {
if (!head) return;
ListNode* temp = head;
head = head->next;
delete temp;
}
```
- 删除特定值的节点:
```cpp
void deleteNodeByValue(ListNode*& head, int val) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr && curr->val != val) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) return;
if (prev == nullptr) head = curr->next;
else prev->next = curr->next;
delete curr;
}
```
阅读全文