创建一个链表,链表内有五个体重身高两个变量,对链表实行插入删除和排序
时间: 2023-11-09 14:07:00 浏览: 28
链表节点定义如下:
```python
class ListNode:
def __init__(self, height, weight):
self.height = height
self.weight = weight
self.next = None
```
创建链表:
```python
# 创建链表
head = ListNode(170, 60)
node1 = ListNode(175, 65)
node2 = ListNode(180, 70)
node3 = ListNode(165, 55)
node4 = ListNode(185, 75)
head.next = node1
node1.next = node2
node2.next = node3
node3.next = node4
```
插入节点:
```python
# 在链表头部插入节点
new_node = ListNode(190, 80)
new_node.next = head
head = new_node
# 在链表中间插入节点
new_node = ListNode(172, 62)
node = head.next
head.next = new_node
new_node.next = node
# 在链表尾部插入节点
new_node = ListNode(168, 58)
node = head
while node.next:
node = node.next
node.next = new_node
```
删除节点:
```python
# 删除链表头部节点
head = head.next
# 删除链表中间节点
node = head
while node.next:
if node.next.height == 175:
node.next = node.next.next
break
node = node.next
# 删除链表尾部节点
node = head
while node.next.next:
node = node.next
node.next = None
```
排序节点:
```python
# 冒泡排序
def bubble_sort(head):
if not head:
return None
end = None
while end != head.next:
node = head
while node.next != end:
if node.height > node.next.height:
node.height, node.next.height = node.next.height, node.height
node.weight, node.next.weight = node.next.weight, node.weight
node = node.next
end = node
bubble_sort(head)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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)
![](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)