Python单向链表
时间: 2024-03-17 19:39:14 浏览: 97
Python单向链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。链表中的节点按照顺序连接在一起,形成一个链式结构。
下面是Python单向链表的基本实现方式:
1. 定义节点类:首先定义一个节点类,包含两个属性:数据元素和指向下一个节点的指针。
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
```
2. 定义链表类:链表类包含若干个节点,以及对链表进行操作的方法。
```python
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert(self, data, position):
new_node = Node(data)
if position == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
if current.next is None:
raise IndexError("Index out of range")
current = current.next
new_node.next = current.next
current.next = new_node
def delete(self, position):
if self.head is None:
raise IndexError("Index out of range")
if position == 0:
self.head = self.head.next
else:
current = self.head
for _ in range(position - 1):
if current.next is None:
raise IndexError("Index out of range")
current = current.next
if current.next is None:
raise IndexError("Index out of range")
current.next = current.next.next
def get(self, position):
if self.head is None:
raise IndexError("Index out of range")
current = self.head
for _ in range(position):
if current.next is None:
raise IndexError("Index out of range")
current = current.next
return current.data
def size(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
```
以上是一个简单的Python单向链表的实现,包括了向链表末尾添加节点、在指定位置插入节点、删除指定位置的节点、获取指定位置的节点值以及获取链表长度等基本操作。
阅读全文