单链表的创建(头插法、尾插法)、插入、删除、查找的代码
时间: 2024-10-02 09:03:45 浏览: 83
单链表是一种线性的数据结构,其中每个节点包含数据和指向下一个节点的指针。以下是单链表的创建(头插法和尾插法)、插入、删除和查找的基本操作。
1. **创建(头插法**):
```c++
// 定义链表节点结构
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 使用头插法创建链表
ListNode* createList(vector<int>& nums) {
if (nums.empty()) return nullptr;
ListNode* head = new ListNode(nums[0]);
ListNode* tail = head;
for (int i = 1; i < nums.size(); ++i) {
tail->next = new ListNode(nums[i]);
tail = tail->next;
}
return head;
}
```
2. **创建(尾插法**):
```c++
ListNode* tailInsert(ListNode*& head, int val) {
if (!head) {
head = new ListNode(val);
return head;
}
ListNode* tail = head;
while (tail->next) {
tail = tail->next;
}
tail->next = new ListNode(val);
return head;
}
```
3. **插入(按值)**:
```c++
void insertNode(ListNode* &head, int value, int index) {
if (index <= 0) {
ListNode* newNode = new ListNode(value);
newNode->next = head;
head = newNode;
} else {
ListNode* current = head;
for (int i = 0; i < index - 1 && current != nullptr; ++i) {
current = current->next;
}
if (current != nullptr) {
ListNode* newNode = new ListNode(value);
newNode->next = current->next;
current->next = newNode;
}
}
}
```
4. **删除**:
```c++
void deleteNode(ListNode* &head, int target) {
if (!head) return;
if (head->val == target) {
ListNode* temp = head;
head = head->next;
delete temp;
return;
}
ListNode* current = head;
while (current->next && current->next->val != target) {
current = current->next;
}
if (current->next) {
ListNode* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
}
}
```
5. **查找**:
```c++
ListNode* searchNode(ListNode* head, int target) {
ListNode* current = head;
while (current != nullptr) {
if (current->val == target) {
return current;
}
current = current->next;
}
return nullptr; // 如果未找到,返回nullptr
}
```
阅读全文