1

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

我的程序应该创建一个Node class,使用函数(数字 n,然后接收 n 个元素)获取用户输入create(),并具有将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
4

1 回答 1

0

您可以只定义一个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)
于 2020-01-04T21:31:58.757 回答