如何在python中的特定索引,无序列表中设置列表中的节点数据?

时间:2017-04-05 12:54:39

标签: python python-3.x

我想创建一个方法,在特定索引处设置列表中的节点数据。 我的节点列表是:

class Node:
    """
    Node class
    """

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

    def get_data(self):
        """
        Returns data
        """
        return self.data

    def get_next(self):
        """
        Gets next node
        """
        return self.next

    def set_data(self, newdata):
        """
        Sets current nodes data
        """
        self.data = newdata

    def set_next(self, newnext):
        """
        Sets next node
        """
        self.next = newnext

我的无序列表类是这样的:

class UnorderedList:
    """
    Unordered list
    """

    def __init__(self):
        self.head = None

    def add(self, item):
        """
        Add item to list
        """
        temp = Node(item)
        temp.set_next(self.head)
        self.head = temp

    def set(self, index, newdata):
        """
        Set node-data in list at specific index
        """
        current = self.head
        for i in range(index):
            current = current.get_next()
        if current != None:
            temp = Node(newdata)
            temp.set_next(current.get_next())
            current.set_next(temp)
        else:
            raise("index out of range")

    def print_list(self):
        """
        Prints each item in list
        """
        # Traversera listan och gör en print() på varje element
        result = "["
        node = self.head
        if node != None:
            result += str(node.data)
            node = node.next
            while node:
                result += ", " + str(node.data)
                node = node.next
        result += "]"
        return result

当您尝试在列表中添加项目时,它非常有效:

myListTwo = UnorderedList()
myListTwo.add(4)
myListTwo.add(50)
myListTwo.add(6)
myListTwo.add(10)
myListTwo.add(60)

print(myListTwo.print_list())

比得到清单:

[60, 10, 6, 50, 4]

问题是当我尝试将节点数据放在特定索引的列表中时,得到了这个结果:

myListTwo.set(2, 70)
print(myListTwo.print_list())

我得到了这个结果:

[60, 10, 6, 70, 50, 4]

你在索引3处是70而不是在索引2,任何想法?

2 个答案:

答案 0 :(得分:1)

这与预期的一样:在第i个节点之后插入新节点 。因此,在您的示例中,您正确地找到第三个节点(6),并在其后立即插入节点70

一个简单的解决方法可能是:

def set(self, index, newdata):
    """
    Set node-data in list at specific index
    """
    current = self.head
    previous = None
    for i in range(index):
        previous = current
        current = current.get_next()
    if current != None:
        temp = Node(newdata)
        temp.set_next(current)
        if previous is None:
            self.head = temp
        else:
            previous.set_next(temp)
    else:
        raise("index out of range")

答案 1 :(得分:0)

我将循环更改为 for i in range(index - 1)