代碼即註釋如下
import sys
import json
class ListNode:
"""
定義一個節點,包括value 和next指針,指向下一個node
"""
def __init__(self, x):
self.val = x
self.next = None
def stringToIntegerList(input):
return json.loads(input)
def stringToListNode(input):
# Generate list from the input
numbers = stringToIntegerList(input)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot # 3.複製一個實例對象(可變變量,ptr屬性變,dummyRoot 也會變,ptr賦值變,dummyRoot 不變)
for number in numbers: # [1,2,3]
ptr.next = ListNode(number) # 4. ListNode(val =0 ,next=ListNode(val =1 ,next=None))
ptr = ptr.next # 5. ptr=ListNode(val=1 ,next=None)
# 第一層: dummyRoot: ListNode(val =0 ,next=ListNode(val =1 ,next=None))
# 第二層: dummyRoot: ListNode(val =0 ,next=ListNode(val =1 ,next=ListNode(val =2 ,next=None)))
ptr = dummyRoot.next # 最後 ptr在dummyRoot的基礎上去掉了val=0
return ptr
def prettyPrintLinkedList(node):
while node and node.next:
print(str(node.val) + "->", end='')
node = node.next
if node:
print(node.val)
else:
print("Empty LinkedList")
def main():
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines() # 1.獲取一個生成器
while True:
try:
line = next(lines) # 2.暫停代碼, 通過next()獲取生成輸入的字符串列表
node = stringToListNode(line)
prettyPrintLinkedList(node)
except StopIteration:
break
if __name__ == '__main__':
main()
pt結構如下圖
![在這裏插入圖片描述]()