首页 > 其他 > 详细

[LeetCode] 206. 反转链表

时间:2019-08-17 22:28:06      阅读:87      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/reverse-linked-list/

题目描述:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:

迭代

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        prev = None
        cur = head
        while cur:
            # 保持下一个节点
            nxt = cur.next
            # 翻转
            cur.next = prev
            # 进行下一个
            prev = cur
            cur = nxt
        return prev

递归:

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next: return head
        new_head = self.reverseList(head.next)
        next_node = head.next
        next_node.next = head
        head.next = None
        return new_head

[LeetCode] 206. 反转链表

原文:https://www.cnblogs.com/powercai/p/11370300.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!