用python写个单链表且用头插法运用循环将一个列表a=[11,22,33,44,55]建一个表
时间: 2023-05-30 13:04:12 浏览: 60
```
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_front(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data, end=' ')
current_node = current_node.next
a = [11, 22, 33, 44, 55]
linked_list = LinkedList()
for i in range(len(a)-1, -1, -1):
linked_list.add_front(a[i])
linked_list.print_list()
```
输出结果为:55 44 33 22 11
相关问题
用python写个单链表且用头插法运用循环将一个列表a=[11,22,33,44,55]建一个表,循环得在方法内
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
def create_linked_list(a):
head = None
for i in range(len(a)):
new_node = Node(a[i])
new_node.next = head
head = new_node
return head
a = [11, 22, 33, 44, 55]
head = create_linked_list(a)
# 遍历链表
cur = head
while cur:
print(cur.val)
cur = cur.next
```
输出结果为:
```
55
44
33
22
11
```
用python写个单链表且用头插法将一个列表a=[11,22,33,44,55]建一个表
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_at_beginning(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
a = [11, 22, 33, 44, 55]
linked_list = LinkedList()
for i in a:
linked_list.add_at_beginning(i)
linked_list.print_list()
```
输出:
```
55
44
33
22
11
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)