# Linked List
class Node:
def __init__(self):
self.data=None
self.next=None
def setData(self,data):
self.data=data
def getData(self):
return self.data
def setNext(self,next):
self.next=next
def getNext(self):
return self.next
class LinkedList:
def BuildList(self):
print("Enter the array :-")
x=int(input("Enter the number :-"))
newNode=Node()
start=Node()
head=Node()
head=start
start=0
while(x!=-1):
newNode.setData(x)
if(start==0):
newNode.setNext(None)
start=newNode
else:
ptr=start
while(ptr.getNext()!=None):
ptr=ptr.getNext()
ptr.setNext(newNode)
newNode.setNext(None)
x=int(input())
print("Thus the list is ")
ptr=start
while(ptr!=None):
print("The data is %d",ptr.getData())
ptr=ptr.getNext()
charan=LinkedList()
charan.BuildList()
答案 0 :(得分:0)
两个问题:
您要多次将newNode
添加到链接列表,但只创建一次。这会创建对一个对象的多个引用;您可能希望对每个独立对象进行单一引用。
print
语句中的百分比样式字符串插值语法错误。
将newNode=Node()
移至while循环内部,并将print语句更改为print("The data is %d" % ptr.getData())
。
# Linked List
class Node:
def __init__(self):
self.data=None
self.next=None
def setData(self,data):
self.data=data
def getData(self):
return self.data
def setNext(self,next):
self.next=next
def getNext(self):
return self.next
class LinkedList:
def BuildList(self):
print("Enter the array :-")
x=int(input("Enter the number :-"))
start=Node()
head=Node()
head=start
start=0
while(x!=-1):
newNode=Node()
newNode.setData(x)
if(start==0):
newNode.setNext(None)
start=newNode
else:
ptr=start
while(ptr.getNext()!=None):
ptr=ptr.getNext()
ptr.setNext(newNode)
newNode.setNext(None)
x=int(input())
print("Thus the list is ")
ptr=start
while(ptr!=None):
print("The data is %d" % ptr.getData())
ptr=ptr.getNext()
charan=LinkedList()
charan.BuildList()
结果:
Enter the array :-
Enter the number :-1
2
3
-1
Thus the list is
The data is 1
The data is 2
The data is 3