python实现单链表的数据结构
时间: 2023-10-10 12:08:01 浏览: 89
好的,可以的。下面是Python实现单链表的代码示例:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
newNode = Node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = newNode
def length(self):
cur = self.head
total = 0
while cur.next!=None:
total+=1
cur = cur.next
return total
def display(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
```
你可以通过append()方法向链表中添加元素,length()方法获取链表长度,display()方法显示链表元素。
希望对你有帮助!
阅读全文