【问题标题】:Create a linked list function without creating another class创建一个链表函数而不创建另一个类
【发布时间】:2020-04-22 23:02:52
【问题描述】:

我正在使用链表进行一些练习,但我被一个函数卡住了。

我的程序应该创建一个Node class,使用create() 函数(数字n 然后接收n 个元素)获取用户输入,并有一个函数printLinkedList(p) 将其打印出来。到目前为止,这很有效,但是我应该创建另一个函数,我将在其中删除最大元素(如果它多次出现,请删除第一次出现)。

我找到了一个查找最大值的函数 findMaxElement(p),但是,它在我的代码中不起作用(例如,我收到 AttributeError: 'Node' object has no attribute 'head' 错误)

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

def create():
    n = int(input())
    if n == 0:
        return None
    s = input().split()
    p = Node(int(s[0]))
    k = p
    for i in range(1, n):
        t = Node(int(s[i]))
        k.next = t
        k = t
    return p

def printLinkedList(p):
    if p == None:
        print('Empty')
        return
    s = p
    while s != None:
        print(s.data, end = " ")
        s = s.next
    print()

def findMaxElement(p):
    current = p.head    
    #Initializing max to initial node info    
    maximum = p.head.data    
    if(p.head == None):    
       print("List is empty")
    else:    
        while(True):    
            #If current node's info is greater than max    
            #Then replace value of max with current node's info    
            if(maximum < current.info):    
                maximum = current.info    
            current= current.next  
            if(current == p.head):    
                break
    return "Maximum value node in the list: "+ str(maximum) 

#Driver code
a = create()
printLinkedList(a)  

输入:

6
1 7 4 2 6 7

预期结果:

1 7 4 2 6 7
1 4 2 6 7

【问题讨论】:

  • 很难用所有这些单字符变量名来理解你的代码。你在为你的findMaxElement 函数提供什么?您必须将列表本身作为参数提供给它,而不是 Node 对象。
  • 是的,您为什么希望p.head 工作?您不能指望只复制另一个为与另一个类定义一起工作而编写的算法来与您的一起工作。当然它不仅可以工作(注意,它似乎假设您实际上编写了一个链表类,它在内部管理节点,无论如何您通常应该这样做)。
  • @po.pe 我想将findMaxElement(a) 添加到驱动程序代码中,因为我无法创建列表
  • @po.pe 不太可能,它是为与典型的链表实现一起工作而编写的函数
  • 听起来很合理:) @Yira,你了解你的代码吗?我的印象是这些是从其他不同项目复制的 sn-ps。

标签: python python-3.x linked-list


【解决方案1】:

您可以定义一个 findMaxElement() 以与 printLinkedList() 函数相同的方式遍历链表(并在此过程中找到最大值):

def findMaxElement(p):
    if p == None:
        return 'Empty List!'
    current = p
    maximum = p.data
    while current != None:  # Not end of list.
        if current.data > maximum:
            maximum = current.data
        current = current.next
    return "Maximum value node in the list: " + str(maximum)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 2022-07-29
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多