数据结构单链表删除
时间: 2023-12-21 20:32:18 浏览: 74
数据结构-线性表-单链表的查找、插入、删除.doc
单链表的删除操作可以分为两种情况:删除头节点和删除非头节点。
1. 删除头节点:
首先,将头节点的下一个节点作为新的头节点,然后释放原来的头节点即可完成删除操作。
2. 删除非头节点:
首先,找到要删除节点的前一个节点,将其指针指向要删除节点的下一个节点,然后释放要删除的节点即可完成删除操作。
以下是两种情况的示例代码:
1. 删除头节点:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def delete_head(self):
if self.head is None:
return
self.head = self.head.next
# 创建链表
linked_list = LinkedList()
# 添加节点
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
linked_list.head = node1
node1.next = node2
node2.next = node3
# 删除头节点
linked_list.delete_head()
```
2. 删除非头节点:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def delete_node(self, key):
if self.head is None:
return
curr = self.head
prev = None
while curr:
if curr.data == key:
break
prev = curr
curr = curr.next
if curr is None:
return
prev.next = curr.next
# 创建链表
linked_list = LinkedList()
# 添加节点
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
linked_list.head = node1
node1.next = node2
node2.next = node3
# 删除节点值为2的节点
linked_list.delete_node(2)
```
阅读全文