链表的操作:1、构建空表H,插入 {"a","b",",","f"} 遍历输出单链表H 输出单链表H的长度 判断单链表H是否为空 输出单链表H的第3个元素 输出元素c的位置 在第5个位置之前插入元素e后,输出单链表 删除H的第了个元素,输出单链表H
时间: 2023-12-29 21:02:29 浏览: 57
链表的操作:
1. 构建空表H
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
H = ListNode()
```
2. 插入 {"a","b",",","f"}
```python
H = ListNode()
curr = H
for val in ["a", "b", ",", "f"]:
curr.next = ListNode(val)
curr = curr.next
```
3. 遍历输出单链表H
```python
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```
4. 输出单链表H的长度
```python
curr = H.next
count = 0
while curr:
count += 1
curr = curr.next
print(count)
```
5. 判断单链表H是否为空
```python
if H.next:
print("H is not empty.")
else:
print("H is empty.")
```
6. 输出单链表H的第3个元素
```python
curr = H.next
for i in range(2):
curr = curr.next
print(curr.val)
```
7. 输出元素c的位置
```python
curr = H.next
pos = 0
while curr:
pos += 1
if curr.val == "c":
print(f"Position of c is {pos}.")
break
curr = curr.next
else:
print("c is not in the list.")
```
8. 在第5个位置之前插入元素e后,输出单链表
```python
curr = H.next
pos = 0
while curr:
pos += 1
if pos == 4:
new_node = ListNode("e")
new_node.next = curr.next
curr.next = new_node
break
curr = curr.next
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```
9. 删除H的第了个元素,输出单链表H
```python
H.next = H.next.next
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```
阅读全文