9/100. Reverse Linked List

在这里插入图片描述

  • 非递归算法:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pFront = None
        pNode = head
        while pNode:
            pNext = pNode.next
            pNode.next = pFront
            pFront = pNode
            pNode = pNext
        return pFront
  • 递归算法:
    def reverseList(self, head):
        if not head or not head.next:
            return head
        pre = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return pre

猜你喜欢

转载自blog.csdn.net/weixin_39010770/article/details/83895706