Добавить функцию узла, не работающую в односвязном списке python

#python #singly-linked-list

#python #односвязный список

Вопрос:

Я новичок, изо всех сил пытаюсь понять и реализовать односвязный список, который добавляет элементы в конец. Я полагаю, что единственный код, который не работает, — это функция добавления, логику для которой я не могу понять. Я полагаю, что хочу установить первый узел в качестве заголовка, а затем вставить каждый другой элемент в хвост, изменив указатель для заголовка, чтобы он указывал на 2-й элемент при его добавлении, затем указатель для 2-го элемента, чтобы он указывал на третий и т.д., Но не могу понять, как это кодировать (чтобы иметь дело с неизвестным количеством строк, здесь 3 для простоты.

 strings = ["one", "two", "three"]


class Node:
    def __init__(self,data,nextNode=None):
        # populate the Node, with data and pointer
        self.data = data
        self.nextNode = nextNode

    def getData(self):
        # method to get value of this node
        return self.data

    def setData(self,val):
        # set value of node to val
        self.data = val

    def getNextNode(self):
        # get the pointer to the next node
        return self.nextNode

    def setNextNode(self,val):
        # set pointer to the next node
        self.nextNode = val

class LinkedList:

    def __init__(self, head = None, tail = None):
        # initial properties of linked list, size 0
        self.head = head
        self.tail = tail
        self.size = 0

    def getSize(self):
        # get size of linked list
        return self.size

    def addNode(self,data):
        # Head should point to first node, which will have a value, and a Null pointer
        if (self.size == 0):
            newNode = Node(data, self.tail)
            self.head.getNextNode() = newNode
        else:
        # All additional nodes should be inserted at tail, and with the pointers for the prior nodes changed to point to the new node
            newNode = Node(data, self.tail)
            self.tail = newNode
            self.size  = 1
            return True

    def printNode(self):
        curr = self.head
        while curr:
            print(curr.data)#, curr.nextNode)
            curr = curr.getNextNode()

mylist = LinkedList()

for i in strings:
    mylist.addNode(i)

mylist.printNode()

# desired output: Head -> one --> two --> three/Tail
  

Ответ №1:

Было много мелких ошибок, пожалуйста, найдите их в коде ниже. И дайте мне знать, если вы чего-то не понимаете.

Одним из важных изменений является то, что новый узел не должен иметь доступа к своему следующему узлу. Это уже последний узел, поэтому рядом с ним не может быть никакого узла. Также, пожалуйста, обратите пристальное внимание на else блок addNode функции.

 strings = ["one", "two", "three","four","five"]

class Node:
    def __init__(self,data):
        # populate the Node, with data and pointer
        self.data = data
        self.nextNode = None

    def getData(self):
        # method to get value of this node
        return self.data

    def setData(self,val):
        # set value of node to val
        self.data = val

    def getNextNode(self):
        # get the pointer to the next node
        return self.nextNode

    def setNextNode(self,val):
        # set pointer to the next node
        self.nextNode = val

class LinkedList:

    def __init__(self, head = None, tail = None):
        # initial properties of linked list, size 0
        self.head = head
        self.tail = tail
        self.size = 0

    def getSize(self):
        # get size of linked list
        return self.size

    def addNode(self,data):
        # Head should point to first node, which will have a value, and a Null pointer
        if (self.size == 0):
            self.head = Node(data)
            self.tail = self.head
            self.size = 1
        else:
        # All additional nodes should be inserted at tail, and with the pointers for the prior nodes changed to point to the new node
            newNode = Node(data)
            self.tail.nextNode = newNode
            self.tail = newNode
            self.size  = 1
            return True

    def printNode(self):
        curr = self.head
        while curr:
            print(curr.data)#, curr.nextNode)
            curr = curr.getNextNode()

mylist = LinkedList()

for i in strings:
    mylist.addNode(i)

mylist.printNode()