怎么构建一个有着自定义数据类型的链式结构
时间: 2024-05-05 18:16:30 浏览: 16
链式结构可以用节点(Node)来表示,每个节点包含两个属性:数据(value)和指向下一个节点的指针(next)。我们可以定义一个节点类来表示节点:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
```
然后,我们可以定义一个链式结构类,它包含一个头节点(head)和尾节点(tail)。链式结构类可以提供一些操作,如添加节点、删除节点、查找节点等。
```python
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add(self, value):
node = Node(value)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
def remove(self, value):
if self.head is None:
return
if self.head.value == value:
self.head = self.head.next
if self.head is None:
self.tail = None
return
current = self.head
while current.next is not None:
if current.next.value == value:
current.next = current.next.next
if current.next is None:
self.tail = current
return
current = current.next
def find(self, value):
current = self.head
while current is not None:
if current.value == value:
return current
current = current.next
return None
def __str__(self):
values = []
current = self.head
while current is not None:
values.append(str(current.value))
current = current.next
return ' -> '.join(values)
```
这个链式结构类可以存储任何类型的数据,只需要将数据作为节点的值存储即可。如果需要自定义数据类型,只需要定义一个类来表示该数据类型,然后将该类的对象作为节点的值存储即可。例如,如果要构建一个链式结构来存储学生信息,可以定义一个学生类:
```python
class Student:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def __str__(self):
return f'{self.name} ({self.gender}, {self.age})'
```
然后,可以将学生类的对象作为节点的值存储到链式结构中:
```python
students = LinkedList()
students.add(Student('Alice', 20, 'female'))
students.add(Student('Bob', 21, 'male'))
students.add(Student('Charlie', 22, 'male'))
print(students) # Alice (female, 20) -> Bob (male, 21) -> Charlie (male, 22)
alice = students.find(Student('Alice', 20, 'female'))
students.remove(alice.value)
print(students) # Bob (male, 21) -> Charlie (male, 22)
```