leetcode_206(翻转列表)

反转一个单链表。
示例:

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

解答方案:

#方案一:循环(python的多重赋值,是首先解析=右侧各式,然后对=左侧进行赋值)
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return head
        
        frontNode = None
        currentNode = head
        
        while currentNode:
            currentNode.next, frontNode, currentNode = frontNode, currentNode, currentNode.next
            #frontNode, frontNode.next, currentNode = currentNode, frontNode, currentNode.next
            #(此赋值循序也可以,python多重赋值首先计算=右侧,在此只要左右两侧对应即可,与左侧顺序无关)
        return frontNode

#方案二:递归
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next :
            return head              //递归终止条件
        
        headNode = self.reverseList(head.next)
        
        head.next.next = head
        head.next = None
        
        return headNode

 


版权声明:本文为zwzen1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。