//创建一个有头链表 //判空 //求长度 //按位置插入 //显示 //按位置删除 //按数据查找 //按数据修改 //清空 //倒置(逆序) //排序
时间: 2023-12-15 08:03:28 浏览: 68
链表功能有建立,排序,插入,删除,输出
以下是创建一个有头链表的Python代码,以及链表的基本操作:
```python
# 创建一个有头链表
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = ListNode()
# 判空
def is_empty(head):
return head.next == None
# 求长度
def get_length(head):
cur = head.next
count = 0
while cur:
count += 1
cur = cur.next
return count
# 按位置插入
def insert(head, pos, val):
if pos < 0 or pos > get_length(head):
return False
cur = head
for i in range(pos):
cur = cur.next
node = ListNode(val)
node.next = cur.next
cur.next = node
return True
# 显示
def show(head):
cur = head.next
while cur:
print(cur.val, end=' ')
cur = cur.next
print()
# 按位置删除
def delete_by_pos(head, pos):
if pos < 0 or pos >= get_length(head):
return False
cur = head
for i in range(pos):
cur = cur.next
cur.next = cur.next.next
return True
# 按数据查找
def find_by_val(head, val):
cur = head.next
while cur:
if cur.val == val:
return cur
cur = cur.next
return None
# 按数据修改
def modify_by_val(head, old_val, new_val):
cur = head.next
while cur:
if cur.val == old_val:
cur.val = new_val
return True
cur = cur.next
return False
# 清空
def clear(head):
head.next = None
# 倒置(逆序)
def reverse(head):
if head.next == None or head.next.next == None:
return head
pre = None
cur = head.next
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
head.next = pre
return head
# 排序
def sort(head):
if head.next == None or head.next.next == None:
return head
cur = head.next.next
head.next.next = None
while cur:
pre = head
while pre.next and pre.next.val < cur.val:
pre = pre.next
tmp = cur.next
cur.next = pre.next
pre.next = cur
cur = tmp
return head
```
阅读全文