Python LinkedList大小/删除功能不起作用

时间:2017-09-04 04:15:00

标签: python

这是我的节点:

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

    def get_next(self):
      return self.next_node

    def set_next(self, next):
      self.next_node = next

    def get_data(self):
      return self.data

    def set_data(self):
      self.data = data

这是LinkedList本身:

class LinkedList(object):
    def __init__(self, root = None):
      self.root = root
      self.size = 0

    def size(self):
      return self.size

    def insert(self, data):
      new_node = Node (data, self.root)
      self.root = new_node
      self.size += 1

    def delete(self, data):
      this_node = self.root
      prev_node = None
      while this_node:
        if this_node.get_data() == data:
          if prev_node:
            prev_node.set_next(this_node.get_next())
          else:
            self.root = this_node
          self.size -= 1
          return True
        else:
          prev_node = this_node
          this_node = this_node.get_next()
      return False

    def search(self, data):
      this_node = self.root
      while this_node:
        if this_node.get_data() == data:
          return data
        else:
          self.root = this_node.get_next()
        return None

    def printLL(self):
      this_node = self.root
      while this_node:
        print(this_node.data)
        this_node  = this_node.get_next()

最后,这些是我正在进行的测试:

ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.printLL()
ll.delete(2)
ll.printLL()
if ll.search(2):
    print("Value 2 found")
else:
    print("Value 2 not found")
if ll.search(1):
    print("Value 1 found")
else:
    print("Value 1 not found")
ll.insert(4)
ll.printLL()
print(str(ll.size()))

我目前正在获得此输出:

2
1
2
1
Value 2 found
Value 1 not found
4
1
Traceback (most recent call last):
  File "C:\Users\ErikIngvoldsen\Documents\Python Code\TestCode.py", line 71, in <module>
    print(str(ll.size()))
TypeError: 'int' object is not callable

为什么对象不可调用?另外,为什么我的删除功能不起作用?作为参考,这是我的输出应该是什么样的:

2 1
1
Value 2 not found
Value 1 found
4 1
2

还有格式化问题,但现在我只关注让它正常工作。

1 个答案:

答案 0 :(得分:0)

size是实例变量,而不是linkedlist类的方法。你不能调用变量。那就是错误。而不是import Control.Monad ((<=<)) -- A couple helpers for indexing lists. index :: Int -> [a] -> Maybe a index _ [] = Nothing index 0 (x:_) = x index n (_:xs) = index (n-1) xs index2 :: (Int,Int) -> [[a]] -> Maybe a index2 (x,y) = index x <=< index y -- index2 uses Maybe's monadic structure, and I think it's quite pretty. -- But if you're not ready for that, you might prefer index2' (x,y) xss | Just xs <- index y xss = index x xs | otherwise = Nothing getConnectedArea' :: (Eq a) => [[a]] -> Point -> a -> [a] getConnectedArea' habitat point nullValue = Set.toList $ getConnectedArea nonnull point where nonnull :: Point -> Bool nonnull p = case index2 p habitat of Nothing -> False Just x -> x /= nullValue ,而是print(str(ll.size()))