[LeetCode] 206. 反转链表

题目链接: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

posted on 2019-08-17 20:48  威行天下  阅读(183)  评论(0编辑  收藏  举报

导航