有关链表的LeetCode做题笔记合集,Python实现
链表定义
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
206. 反转链表 Reverse Linked List
遍历链表,迭代前节点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