用python实现数据表和链表
时间: 2023-08-10 10:28:31 浏览: 45
数据表和链表都是常见的数据结构,在Python中可以通过类来实现。
下面是一个简单的数据表实现:
```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]
```
这个类可以创建一个指定大小的数据表,并提供设置和获取单元格值的方法。
下面是一个简单的链表实现:
```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
```
这个类可以创建一个链表,并提供添加节点和打印链表的方法。每个节点包含一个值和指向下一个节点的指针。