leetcode206. 反转链表
题目
代码
新链表逐个存储
- 提取单个节点,添加到新链表的头结点处
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:new_node = Nonecurrent = headwhile current:rest = current.nexttemp_head = currenttemp_head.next = new_nodenew_node = temp_headcurrent = restreturn new_node
原地修改指向:双指针法
- 初始化node_left为None,然后先保存node_right.next,再将node_right.next指向node_left即可
class Solution:def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:node_left = Nonenode_right = headwhile node_right:rest = node_right.nextnode_right.next = node_leftnode_left = node_rightnode_right = restreturn node_left
原地修改指向:递归法
class Solution:def reverseList(self, head: ListNode) -> ListNode:return self.reverse(head, None)def reverse(self, cur: ListNode, pre: ListNode) -> ListNode:if cur == None:return pretemp = cur.nextcur.next = prereturn self.reverse(temp, cur)