用python实现完整的数据表和链表
时间: 2024-03-06 16:46:45 浏览: 20
下面是一个完整的数据表实现:
```python
class DataTable:
def __init__(self, rows, columns):
self.data = [[None for _ in range(columns)] for _ in range(rows)]
self.rows = rows
self.columns = columns
def set_value(self, row, column, value):
self.data[row][column] = value
def get_value(self, row, column):
return self.data[row][column]
def __str__(self):
return '\n'.join(['\t'.join([str(cell) for cell in row]) for row in self.data])
```
这个类除了提供设置和获取单元格值的方法外,还实现了`__str__`方法,可以将整个数据表以字符串形式输出。
下面是一个完整的链表实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, val):
if not self.head:
self.head = ListNode(val)
else:
current = self.head
while current.next:
current = current.next
current.next = ListNode(val)
def print_list(self):
current = self.head
while current:
print(current.val)
current = current.next
def __str__(self):
current = self.head
values = []
while current:
values.append(str(current.val))
current = current.next
return ' -> '.join(values)
```
这个类除了提供添加节点和打印链表的方法外,还实现了`__str__`方法,可以将整个链表以字符串形式输出。