链表的基本操作python
时间: 2023-09-05 18:14:39 浏览: 53
链表是一种常见的数据结构,它由一系列节点组成,每个节点都包含一个值和一个指向下一个节点的指针。
在Python中,我们可以使用类来表示链表和节点。
首先,我们定义一个节点类:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
```
然后,我们定义一个链表类,包含一些基本操作:
1. 初始化链表
```python
class LinkedList:
def __init__(self):
self.head = None
```
2. 在链表头部插入节点
```python
def insert_at_head(self, value):
new_node = Node(value)
new_node.next = self.head
self.head = new_node
```
3. 在链表尾部插入节点
```python
def insert_at_tail(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
```
4. 在指定位置插入节点
```python
def insert_at_position(self, position, value):
if position <= 0:
self.insert_at_head(value)
else:
new_node = Node(value)
count = 0
current = self.head
while current and count < position - 1:
current = current.next
count += 1
if not current:
raise IndexError("Position out of range")
new_node.next = current.next
current.next = new_node
```
5. 删除指定值的节点
```python
def delete(self, value):
if not self.head:
return
if self.head.value == value:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.value == value:
current.next = current.next.next
return
current = current.next
```
6. 打印链表
```python
def print_list(self):
current = self.head
while current:
print(current.value, end=" ")
current = current.next
print()
```
以上就是链表的基本操作,你可以根据需要进行调用。