写一下单链表基本操作删除操作的代码
时间: 2024-09-27 10:11:54 浏览: 38
在单链表中,删除一个节点通常需要处理两种情况:删除头节点和删除非头节点。这里我会给出两个示例,分别是使用指针在C++和Python中的实现:
**C++ 示例(使用迭代法):**
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
// 删除头节点
Node* deleteFirst(Node* head) {
if (head == nullptr) return nullptr; // 如果链表为空
Node* temp = head;
head = head->next;
delete temp; // 释放原头节点
return head;
}
// 删除指定位置的节点(假设已知节点值)
Node* deleteNodeByValue(Node* head, int value) {
if (head == nullptr) return nullptr;
Node* prev = nullptr;
Node* curr = head;
while (curr != nullptr && curr->data != value) {
prev = curr;
curr = curr->next;
}
if (curr == nullptr) return head; // 没找到要删除的节点
if (prev == nullptr) head = curr->next; // 删除头节点
else prev->next = curr->next; // 删除中间节点
delete curr; // 释放内存
return head;
}
```
**Python 示例:**
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# 删除头节点
def delete_first(head):
if not head:
return None
head = head.next
del head # Python中直接删除对象
return head
# 删除指定值的节点
def delete_node_by_value(head, value):
if not head:
return head
current = head
previous = None
while current and current.data != value:
previous = current
current = current.next
if current is None:
return head
if previous is None:
head = current.next
else:
previous.next = current.next
del current # Python中直接删除对象
return head
```
阅读全文