python閾捐〃杞崲涓簂ist鎬庝箞瀹炵幇
瑕佸皢涓€涓摼琛ㄨ浆鎹负涓€涓垪琛紝鍙互浣跨敤杩唬鐨勬柟娉曚緷娆¢亶鍘嗛摼琛ㄧ殑鑺傜偣锛屽苟灏嗚妭鐐圭殑鍊兼坊鍔犲埌鍒楄〃涓€備笅闈㈡槸涓€涓ず渚嬩唬鐮侊細
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def linkedListToList(head):
result = [] # 鍒涘缓涓€涓┖鍒楄〃鐢ㄤ簬瀛樺偍閾捐〃鐨勫€?/span>
node = head # 浠庡ご鑺傜偣寮€濮嬮亶鍘嗛摼琛?/span>
while node: # 褰撹妭鐐逛笉涓虹┖鏃?/span>
result.append(node.val) # 灏嗚妭鐐圭殑鍊兼坊鍔犲埌鍒楄〃涓?/span>
node = node.next # 绉诲姩鍒颁笅涓€涓妭鐐?/span>
return result
浣跨敤绀轰緥锛?/p>
# 鍒涘缓涓€涓摼琛細1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
head.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
# 灏嗛摼琛ㄨ浆鎹负鍒楄〃
result = linkedListToList(head)
print(result) # 杈撳嚭锛歔1, 2, 3, 4, 5]
閫氳繃閬嶅巻閾捐〃鐨勮妭鐐癸紝渚濇灏嗚妭鐐圭殑鍊兼坊鍔犲埌鍒楄〃涓紝鏈€缁堣幏寰椾簡閾捐〃杞崲涓虹殑鍒楄〃銆?/p>
相关问答