leetcode 206. Reverse Linked List
2023-09-14 09:11:53 时间
Reverse a singly linked list.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None pre_node = head next_node = head.next pre_node.next = None while next_node: tmp = next_node.next next_node.next = pre_node pre_node = next_node next_node = tmp return pre_node
精简下代码:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None pre_node = None cur_node = head while cur_node: tmp = cur_node.next cur_node.next = pre_node pre_node = cur_node cur_node = tmp return pre_node
递归解:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ def reverse_node(pre_node, cur_node): if not cur_node: return pre_node next_node = cur_node.next cur_node.next = pre_node return reverse_node(cur_node, next_node) if not head: return None new_head = reverse_node(head, head.next) head.next = None return new_head
dfs
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head node = self.reverseList(head.next) head.next.next = head head.next = None return node
记得程序员面试金典里专门提过!
相关文章
- LeetCode笔记:Weekly Contest 305
- LeetCode周赛306,用原题,你对得起我们吗,日内瓦,退钱!
- 【day04】力扣(LeetCode)每日一刷[1306. 跳跃游戏 III ][703. 数据流中的第 K 大元素 ][1337. 矩阵中战斗力最弱的 K 行]
- JavaScript刷LeetCode拿offer-js版字典
- LeetCode-84-柱状图中最大的矩形
- LeetCode 刷题常用数据结构(Go 篇)
- LeetCode_1-两数之和
- 创建list ALV tree[RS_TREE_LIST_DISPLAY]详解编程语言
- 利用Redis实现List元素的排序(redis排序list)
- 利用Redis构建新的List存储方式(redis存储list)
- Redis 轻松存储列表数据:使用 Redis 保存 List 的方法(redis保存list)
- 中一部分元素用Redis快速获取List元素(redis获取list)
- 性能优化提升Redis List性能的简单方法(redis的list)
- Mysql实现List存储的技巧(mysql存储list)
- 利用Redis List对象提升系统性能(redis list对象)
- Oracle中使用List命令查看表结构(list命令oracle)
- Redis中List实现快速数据查找(redis 选择list)
- 使用XmlSerializer序列化List对象成XML格式(list对象序列化)