Код, приведенный ниже, показывает объектно-ориентированную реализацию связанного списка в Python 3.7.Здесь я определил класс с именем Node, и под этим классом я определил функцию delete, которая принимает два параметра: 'this' и 'x'.Здесь «this» - текущий / вызывающий объект, а «x» - это значение, которое необходимо найти и удалить из связанного списка.
Теперь проблема заключается в том, что я передаю такое значение для «x».так что это фактически первый узел списка, затем, согласно коду, выполняется указанная ниже строка: this = this.next, так что первый узел удаляется, но когда я отображаю список с помощью функции display () послеуспешный вызов функции delete (), тогда в отображаемом списке все еще есть первый узел (т. е. первый узел не был удален)
Итак, почему это происходит?
class Node:
def __init__(this, data = None):
this.data = data
this.next = None
def append(this, x):
p = this
if this.data == None:
this.data = x
else:
while p.next != None:
p = p.next
p.next = Node(x)
def search(this, x):
p = this
while p != None and p.data != x:
p = p.next
if p == None:
return False
elif p.data == x:
return True
else:
return False
def delete(this, x):
p = this
if this.data == x:
this = this.next
return (True, x)
else:
while p.next.next != None and p.next.data != x:
p = p.next
if p.next.next == None and p.next.data == x:
p.next = None
return (True, x)
elif p.next.data == x:
p.next = p.next.next
return (True, x)
else:
return (False, x)
def display(this):
p = this
if p == None:
print("Empty List")
else:
while p != None:
print(p.data, end = " ")
p = p.next
print("\n")
print("Enter 1 to Append Data")
print("Enter 2 to Search Data")
print("Enter 3 to Delete Data if Exists")
print("Enter 4 to Display the List")
print("Enter 5 to Quit")
List = Node()
while True:
print("Enter your Choice", end = " = ")
choice = int(input())
if choice == 1:
x = int(input("Enter a No. to append = "))
List.append(x)
elif choice == 2:
x = int(input("Enter a No. to Search = "))
if List.search(x):
print("Search SuccessFull")
else:
print("Search Unsucessfull")
elif choice == 3:
x = int(input("Enter a No. to Delete = "))
(p, q) = List.delete(x)
if p == True:
print("Deleted = ", q)
else:
print("Not found : ", q)
elif choice == 4:
List.display()
elif choice == 5:
print("Good Bye")
break
else:
print("Wrong Choice")
# ----- OUTPUT ------#
Enter 1 to Append Data
Enter 2 to Search Data
Enter 3 to Delete Data if Exists
Enter 4 to Display the List
Enter 5 to Quit
Enter your Choice = 1
Enter a No. to append = 20
Enter your Choice = 1
Enter a No. to append = 21
Enter your Choice = 1
Enter a No. to append = 22
Enter your Choice = 1
Enter a No. to append = 23
Enter your Choice = 1
Enter a No. to append = 24
Enter your Choice = 4
20 21 22 23 24
Enter your Choice = 3
Enter a No. to Delete = 20
Deleted = 20
Enter your Choice = 4
20 21 22 23 24
См. После удаления 20 Мы ожидаем, что список 21 22 23 24, но это не так!