带有两个类Node和LinkedList的单链表很容易实现。然而,我的问题是,当涉及到一个单一链接列表只有第一个节点访问(没有存储的长度,没有最后一个节点的访问,没有使用虚拟节点)。特殊的方法,我不能绕到我的头或找到很多关于在线类似于内置列表操作与O(1)复杂蟒蛇,比如如下:在python中使用特殊方法的单链表,被卡住
aa = LinkedList() -- creates empty list
aa.first() -- similar to aa[0]
aa.rest() -- similar to aa[1:]
aa.cons(item) -- similar to aa[item:]
[item] + aa -- similar to aa.insert(0, item)
任何形式的铅,帮助,指导将不胜感激。出于某种原因,我只是不能将Pythons内置列表操作符解释为LinkedList中我自己的方法,而没有虚拟节点或存储长度和迭代器。看着它,它似乎就像我很近,但我没有或找到的东西似乎有所帮助。谢谢。
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
def __str__(self):
return str(self.data)
def __repr__(self):
return "Node(%s, %s)" % (repr(self.data), repr(self.next))
def __eq__(self, other):
return self.data == other.data and self.next == other.next
class myList:
def __init__(self):
self.first = Node()
def add(self, data):
newNode = Node() # create a new node
newNode.data = data
newNode.next = self.first # link the new node to the 'previous' node.
self.first = newNode # set the current node to the new one
def first(self):
return self.first.data
def __repr__(self):
plist = []
for i in self:
plist.append(i)
return "LinkedList(%s)" % str(plist)
请发布您的当前代码,即使它没有完全正常工作。 – 2012-04-17 01:53:23
就像我说过的,我不知道我现在在做什么,我只是需要一个领导。但是继承了完整的Node类和基本的LinkedList类 – DJXiej 2012-04-17 01:58:24
出于好奇,你是在学习封装和OO编程的课程吗?在Python中,当你可以正常执行'node.data = 5'时,执行像'node.setData(5)'这样的操作有点奇怪。如果你需要控制对它们的访问,你也可以使用装饰器来包装变量。 – 2012-04-17 02:09:55