代码片段如下:试图颠倒我的节点列表,但是当我这样做时,只有一个节点(链接列表中的第一个)打印。任何想法我在这里做错了吗?我已经写在纸上,它似乎应该循环通过我的节点,将每个添加到我的新链接列表? newList.head.next = temp
:问题的如何反转我在Python中的单节点链表节点?
# node class
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
# singly linked list class
class SinglyLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
# I'm trying to do the same thing in my reverseList() method
# as I'm doing in the addFront method
def addFront(self, value):
# create new node
newNode = Node(value)
# set old head to point to new node
if self.head == None:
self.head = newNode
self.tail = newNode
else:
# store old head
last_head = self.head
# set head to new node
self.head = newNode
# point head to old head
self.head.next = last_head
# reverseList() method not working?
# Only giving me first head value? Why?
def reverseList(self):
node = self.head
newList = SinglyLinkedList()
newList.head = None
while node:
if node.next == None:
break
else:
temp = newList.head
newList.head = node
newList.head.next = temp
print newList.head.value
node = node.next
我不能要求更强大的反馈,非常感谢你所描述的所有内容,我现在明白你对功能/命令行为的看法 - 我试图找到这个解决方案,这是我走进势在必行的土地,但你已经完成了(扭转现有的名单)是恒星和我正在寻找的确切解决方案。接受答复并且您的反馈和贡献受到极大的重视! – natureminded