class ListNode(): def __init__(self, val): self.val = val self.next = None
class Solution(): # ====================================================== 核心函数部分 ========================================== def Reverse(self, head: ListNode) -> ListNode: pre = None cur = head while cur: next = cur.next cur.next = pre pre = cur cur = next return pre
def print_list(self, head: ListNode): cur = head while cur: print(str(cur.val) + '->', end=' ') cur = cur.next # ====================================================== 核心函数部分 ==========================================
if __name__ == '__main__': list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = ListNode(list[0]) tail = head for node in list[1:]: tail.next = ListNode(node) tail = tail.next solution = Solution() solution.print_list(head) print('\n\n') pre = solution.Reverse(head) solution.print_list(pre)