목록을 [1,2,3,4,5]와 같은 형식으로 인쇄 할 수있게 해주는 UnorderedList 클래스 용 __str__method를 작성하려고합니다.파이썬 정렬되지 않은 목록 노드 : __str__ 메서드
하지만 몇 가지 이유로 목록의 첫 번째 위치 만 인쇄합니다. 예. [1] 대신 [1,2,3,4,5]
def __str__(self):
result = "["
node = self.head
if node != None:
result += str(node.data)
node = node.next
for i in range(self.num_elements - 1):
result += ", " + str(node.data)
node = node.next
result += "]"
return result
여기
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None
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
class UnorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self,item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
def __str__(self):
result = "["
node = self.head
if node != None:
result += str(node.data)
node = node.next
for i in range(0 - 1):
result += ", " + str(node.data)
node = node.next
result += "]"
return result
어떤 도움이 좋지 않을까 ... 내 노드 및 UnorderedList 클래스 메소드의 나머지 부분입니다. 또한 훨씬 더 쉬운 방법으로 쓰여졌습니다. str. 당신은 잘못을 반복하고
이지만, 목록은 알고 있다면 그 첫 번째 요소가 무엇인지, 각 요소는 다음 요소가 무엇인지 알고 있으므로 순서가 지정되지 않습니다. 나는 당신 수업의 목적이 무엇인지 모르겠다. – BrenBarn
나는 이것이 단지 연결리스트이고 정렬되지 않았다고 생각했다. 그러나 클래스를 "UnorderedList"라고해야하는 과제입니다. 어쩌면 질문 제목을 노드가있는 LinkedList로 변경해야합니까? – Newbie
또한 바보예요 – Newbie