LeetCode 206 反转链表 Reverse Linked List Python

有关链表的LeetCode做题笔记合集,Python实现

链表定义

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

206. 反转链表 Reverse Linked List

LeetCodeCN 第206题链接

遍历链表,迭代前节点prev,缓存当前节点current的下一节点,然后把当前节点的next指针指向前节点prev

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        current = head
        prev = None
        while current:
            tmp = current.next
            current.next = prev
            prev = current
            current = tmp
        return prev

用Python三元交换能同时赋值不需要缓存的特性可以一行完成交换

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        current = head
        prev = None
        while current:
            current.next, prev, current = prev, current, current.next
        return prev

下一题:24. 两两交换链表中的节点 Swap Nodes in Pairs

你可能感兴趣的:(LeetCode 206 反转链表 Reverse Linked List Python)