可以添加一段代码将上述双向列表画图打印吗
时间: 2023-12-19 13:08:00 浏览: 57
当然可以,请参考以下代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
new_node.prev = cur
def prepend(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
self.head.prev = new_node
new_node.next = self.head
self.head = new_node
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
```
我们可以在 `print_list` 方法中添加一些代码,将双向列表画图打印出来:
```python
def print_list(self):
cur = self.head
while cur:
print(" <- ", end="")
print(cur.data, end="")
print(" -> ", end="")
cur = cur.next
print("None")
```
这段代码将会输出以下内容:
```python
<- 1 -> <- 2 -> <- 3 -> <- 4 -> <- 5 -> None
```
其中 `<-` 和 `->` 分别表示节点的前驱和后继。
阅读全文