Python 单链表删除最大值 - 代码示例

本示例代码演示如何使用 Python 创建单链表并删除其中唯一的最大值。代码使用头插法构建链表,并包含详细注释,方便理解。

问题描述: 假设单链表有唯一的最大值,创建一个单链表,并删除其最大值。

提示: 用头插法建立链表

输入形式: 从键盘输入若干个整数,以空格分开,-1作为输入结束。

输出形式: 输出删除最大值后的单链表的所有值。

样例输入: 65 5 6 78 12 -1

样例输出: 12 6 5 65

样例说明:

评分标准:

编程语言: Python

提交源文件内容:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# 头插法建立单链表
def create_linked_list(nums):
    head = Node(None)
    for num in nums:
        node = Node(num)
        node.next = head.next
        head.next = node
    return head.next

# 找到最大值节点及其前驱节点
def find_max_node(head):
    max_node = head
    pre_max_node = None
    cur = head
    while cur:
        if cur.data > max_node.data:
            max_node = cur
            pre_max_node = pre
        pre = cur
        cur = cur.next
    return max_node, pre_max_node

# 删除节点
def delete_node(node, pre_node):
    pre_node.next = node.next
    node.next = None

# 遍历单链表
def traverse_linked_list(head):
    cur = head
    while cur:
        print(cur.data, end=' ')
        cur = cur.next

# 主函数
def main():
    nums = list(map(int, input().split()))
    head = create_linked_list(nums)
    max_node, pre_max_node = find_max_node(head)
    delete_node(max_node, pre_max_node)
    traverse_linked_list(head)

if __name__ == '__main__':
    main()
Python 单链表删除最大值 - 代码示例

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

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