leetcode206. 反转链表

leetcode206. 反转链表

题目

leetcode206. 反转链表_第1张图片

代码

新链表逐个存储

  • 提取单个节点,添加到新链表的头结点处
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        new_node = None
        current = head
        while current:
            rest = current.next
            temp_head = current
            temp_head.next = new_node
            new_node = temp_head
            current = rest
        return 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 = None
        node_right = head

        while node_right:
            rest = node_right.next
            node_right.next = node_left
            node_left = node_right
            node_right = rest

        return 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 pre
        temp = cur.next
        cur.next = pre
        return self.reverse(temp, cur)

你可能感兴趣的:(链表,数据结构)