python " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

python閾捐〃杞崲涓簂ist鎬庝箞瀹炵幇

扬州沐宇科技
2023-12-20 00:04:17
python

瑕佸皢涓€涓摼琛ㄨ浆鎹负涓€涓垪琛紝鍙互浣跨敤杩唬鐨勬柟娉曚緷娆¢亶鍘嗛摼琛ㄧ殑鑺傜偣锛屽苟灏嗚妭鐐圭殑鍊兼坊鍔犲埌鍒楄〃涓€備笅闈㈡槸涓€涓ず渚嬩唬鐮侊細

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>

扫码添加客服微信