почему метод "добавить" не работает правильно? - PullRequest
0 голосов
/ 13 февраля 2019

Метод append работает неправильно.Он идет только внутри инструкции if метода append и не входит в цикл while.

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

class Linkedlist:
    def __init__(self):
        self.head=Node()

    def append(self,data):
        new_node=Node(data)
        if self.head.data is None:
            self.head=new_node          
        cur_node=self.head
        while cur_node.next is not None:
            cur_node=cur_node.next
        cur_node=new_node

    def insert_after_node(self,prev_node,data):
        new_node=Node(data)
        if prev_node is None:
            print("node that you have entered does not exist")
        new_node.next=prev_node.next
        prev_node.next=new_node

    def display(self):
        current=self.head
        while current.next is not None:
            print(current.data)
            current=current.next

List=Linkedlist()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")
List.display()

Ожидаемый результат: AgBC
Фактический результат: A

Ответы [ 2 ]

0 голосов
/ 13 февраля 2019
class Node:
    def __init__(self,data=None):
        self.data=data
        self.next=None

class LinkedList():
    def __init__(self):
        self.head=Node()

    def append(self,data):
        new_node=Node(data)
        if self.head.data is None:
            self.head=new_node
        else:
            cur_node=self.head
            while cur_node.next is not None:
                cur_node=cur_node.next
            cur_node.next=new_node

    def insert_after_node(self,prev_node,data):
        new_node=Node(data)
        if prev_node is None:
            print("node that you have entered does not exist")
        new_node.next=prev_node.next
        prev_node.next=new_node

    def display(self):
        current=self.head
        while current.next is not None:
            print(current.data)
            current=current.next
        print(current.data)

List=LinkedList()
List.append("A")
List.append("B")
List.append("C")
List.insert_after_node(List.head,"g")

Исправлены некоторые ошибки:

  1. Имя класса LinkedList проблема несоответствия

  2. В append, if self.head.data is None, он должен установить self.head и затем вернуть.

  3. В else части append пусть последний узел указывает на новый узел на cur_node.next=new_node

  4. В display также должен быть напечатан последний узел.

0 голосов
/ 13 февраля 2019

Ваш метод .append() просто устанавливает локальную переменную на cur_node, чтобы указывать на new_node.Это не меняет связанный список вообще;последний узел в ссылке, который ранее был назначен этой локальной переменной, не изменяется.

Вместо этого вы хотите присвоить атрибуту .next последнего узла:

cur_node.next = new_node

В противном случае цикл while в методе работает нормально.

Вы также должны не использовать new_node дважды, когда список пуст.Выход, если у вас еще нет головного узла с данными:

if self.head.data is None:
    self.head=new_node
    return

Лично я бы установил self.head = None вместо self.head = Node(), затем использовал бы if self.head is None:.

Затем ваша функция отображения забывает напечатать последний элемент.Вместо того, чтобы проверять current.next, проверьте, является ли current None;вот где установка self.head на None для пустого списка будет работать намного лучше:

def display(self):
    current = self.head
    while current is not None
        print(current.data)
        current = current.next
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...