为什么链接列表的代码在HackerRank中显示错误?

时间:2018-01-23 15:34:08

标签: python data-structures linked-list

我已在IDLE中使用此代码实现了链接列表。如果我遍历它显示预期的输出。但是在黑客中我遇到了麻烦。我错过了什么? 这是问题link

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

    def get_data(self):
        return self.data
    def get_next(self):
        return self.next_node
    def set_next(self,new_next):
        self.next_node = new_next
class LL:
    def __init__(self,head=None,tail=None):
       self.head = head   #head
       self.tail = tail   #tail
    def Insert(self,data):
        new_node =  Node(data) #new_node
        new_node.set_next(None)

        if self.head == None:

            self.head = new_node
            self.tail = new_node
        else:
            self.tail.set_next(new_node)
            self.tail = new_node

2 个答案:

答案 0 :(得分:1)

python中的getter和setter是多余的。而且,你真的过分复杂了。

只需要担心两种情况;一般情况以及headNone时的角落情况。

解决方案1 ​​
迭代

def Insert(head, data):
    # handle the corner case
    if not head:
        return Node(data)

    # handle the general case
    temp = head
    while temp.next:
        temp = temp.next
    temp.next = Node(data)

    return head

解决方案2
递归

def Insert(head, data):
    if not head:
        return Node(data)

    head.next = Insert(head.next, data)
    return head

这两个解决方案都通过了Hackerrank上的所有测试用例。

答案 1 :(得分:0)

在您的代码self.tail.set_next(new_node)中显示错误,因为set_next是类Node的功能,您可以通过Node object

访问此功能

TryThis

class Node:

   def __init__(self,data,nextNode=None):
       self.data = data
       self.nextNode = nextNode

   def getData(self):
       return self.data

   def setData(self,val):
       self.data = val

   def getNextNode(self):
       return self.nextNode

   def setNextNode(self,val):
       self.nextNode = val

class LinkedList:

   def __init__(self,head = None):
       self.head = head
       self.size = 0

   def getSize(self):
       return self.size

   def addNode(self,data):
       newNode = Node(data,self.head)
       self.head = newNode
       self.size+=1
       return True

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

myList = LinkedList()
print("Inserting")
print(myList.addNode(5))
print(myList.addNode(15))
print(myList.addNode(25))
print("Printing")
myList.printNode()
print("Size")
print(myList.getSize())

它的数据结构看起来像 enter image description here