1. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
方法一:
def reverseList(head):
prev = None
cur = head
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
方法二:
def reverseList(head):
lst = []
cur = head
while cur:
lst.append(cur.val)
cur = cur.next
lst.reverse()
new_head = None
for val in lst:
new_node = ListNode(val)
new_node.next = new_head
new_head = new_node
return new_head