用python写链表的创建,打印,
时间: 2023-05-28 17:03:37 浏览: 44
插入和删除操作:
```python
# 定义链表节点类
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 定义链表类
class LinkedList:
def __init__(self):
self.head = None
# 创建链表
def create(self, nums):
if not nums:
return None
self.head = ListNode(nums[0])
curr = self.head
for num in nums[1:]:
node = ListNode(num)
curr.next = node
curr = curr.next
# 打印链表
def print(self):
curr = self.head
while curr:
print(curr.val, end=" ")
curr = curr.next
print()
# 插入节点
def insert(self, val):
node = ListNode(val)
if not self.head:
self.head = node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = node
# 删除节点
def delete(self, val):
if not self.head:
return
if self.head.val == val:
self.head = self.head.next
return
curr = self.head
while curr.next:
if curr.next.val == val:
curr.next = curr.next.next
return
curr = curr.next
```
使用示例:
```python
# 创建链表
l = LinkedList()
l.create([1, 2, 3, 4, 5])
# 打印链表
l.print() # 输出:1 2 3 4 5
# 插入节点
l.insert(6)
# 打印链表
l.print() # 输出:1 2 3 4 5 6
# 删除节点
l.delete(3)
# 打印链表
l.print() # 输出:1 2 4 5 6
```