在不创建另一个类的情况下创建链表函数



我正在做一些带有链表的练习,但我被一个函数卡住了。

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

我找到了一个寻找最大值的函数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(),就像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)

相关内容

最新更新