코드 단편은 다음과 같습니다. 노드 목록을 역으로 만들려고 시도하지만 그렇게하면 링크 된 목록의 첫 번째 노드 만 인쇄됩니다. 내가 여기서 뭘 잘못하고 있는거야? 필자는 이것을 종이에 썼다. 내 노드를 통해 루프를 돌면서 각각을 새로운 링크드 목록에 추가하는 것처럼 보인다. newList.head.next = temp
: 문제의어떻게 파이썬에서 노드의 단일 링크 된 목록을 되돌릴 수 있습니까?
# 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