1. 算法描述
定义函数,输入为链表的head,反转链表并输出反转后链表的head。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
2. 算法实现
基于双指针,一个指针用于获取当前链表对应数值,另一个指针用于构建新的链表。
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return None
pre = head
cur = None
while pre:
# 构建当前值对应的链表
temp = ListNode(pre.val)
# 在cur前面插入构建的链表
temp.next = cur
cur = temp
pre = pre.next
return cur