输入若干个不超过100的整数,建立单链表
时间: 2023-04-27 16:02:43 浏览: 80
好的,以下是建立单链表的代码:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def print_list(self):
current = self.head
while current is not None:
print(current.data, end=' ')
current = current.next
```
使用方法:
```python
# 创建一个空链表
my_list = LinkedList()
# 输入若干个整数,添加到链表中
nums = input("请输入若干个整数,用空格分隔:").split()
for num in nums:
my_list.add_node(int(num))
# 打印链表
my_list.print_list()
```
希望能帮到你!
阅读全文