单链表操作:排序、交集、并集、倒序、合并和复制

本文提供Python伪代码实现单链表的排序、交集、并集、倒序、合并和复制功能,并详细解释每个步骤。

1. 定义单链表节点和插入节点函数

# 定义单链表节点
class ListNode:
    def __init__(self, value):
        self.val = value
        self.next = None

# 定义插入节点函数
def insert_node(head, value):
    new_node = ListNode(value)
    if head is None or value >= head.val:
        new_node.next = head
        return new_node
    else:
        cur = head
        while cur.next and cur.next.val > value:
            cur = cur.next
        new_node.next = cur.next
        cur.next = new_node
        return head

2. 创建两个单链表 a 和 b

# 创建链表 a
a = None
for _ in range(5):
    num = int(input('请输入一个整数:'))
    a = insert_node(a, num)

# 创建链表 b
b = None
for _ in range(5):
    num = int(input('请输入一个整数:'))
    b = insert_node(b, num)

3. 计算单链表 a 和 b 的交集和并集

# 输出链表 a 和 b 的交集和并集
intersection = []
union = []
cur_a = a
cur_b = b
while cur_a and cur_b:
    if cur_a.val == cur_b.val:
        intersection.append(cur_a.val)
        union.append(cur_a.val)
        cur_a = cur_a.next
        cur_b = cur_b.next
    elif cur_a.val < cur_b.val:
        union.append(cur_a.val)
        cur_a = cur_a.next
    else:
        union.append(cur_b.val)
        cur_b = cur_b.next

while cur_a:
    union.append(cur_a.val)
    cur_a = cur_a.next

while cur_b:
    union.append(cur_b.val)
    cur_b = cur_b.next

print('链表a和b的交集为:', intersection)
print('链表a和b的并集为:', union)

4. 将单链表 b 倒序

# 将链表 b 倒序
prev = None
cur = b
while cur:
    temp = cur.next
    cur.next = prev
    prev = cur
    cur = temp
b = prev

5. 合并两个有序单链表为一个有序单链表(从大到小排序)

# 合并两个有序链表为一个有序链表(从大到小排序)
def merge_sorted_lists(a, b):
    dummy = ListNode(0)
    cur = dummy
    while a and b:
        if a.val >= b.val:
            cur.next = a
            a = a.next
        else:
            cur.next = b
            b = b.next
        cur = cur.next
    if a:
        cur.next = a
    if b:
        cur.next = b
    return dummy.next

merged = merge_sorted_lists(a, b)

6. 复制合并后的链表

# 复制合并后的链表
dummy = ListNode(0)
cur = dummy
while merged:
    cur.next = ListNode(merged.val)
    cur = cur.next
    cur.next = ListNode(merged.val)
    cur = cur.next
    merged = merged.next

# 输出复制后的链表
cur = dummy.next
while cur:
    print(cur.val, end=' ')
    cur = cur.next

请注意以上只是伪代码,具体实现可能需要根据具体编程语言进行调整。

单链表操作:排序、交集、并集、倒序、合并和复制

原文地址: https://www.cveoy.top/t/topic/UNL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录