LeetCode 206. 反转链表

作者: freesan44 | 来源:发表于2020-06-07 20:35 被阅读0次

    题目

    反转一个单链表。

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

    进阶:
    你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

    解题思路

    记录一个数组值,然后再遍历重新赋值

    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            tempList = []
            tempHead = head
            while tempHead != None:
                tempList.append(tempHead.val)
                tempHead = tempHead.next
            res = head
            while len(tempList)>0:
                res.val = tempList.pop()
                res = res.next
            return head
    
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            #正统做法
            pre = None
            cur = head
            while cur != None:
                tempNode = cur.next
                cur.next = pre
                pre = cur
                cur = tempNode
            return pre
    

    相关文章

      网友评论

        本文标题:LeetCode 206. 反转链表

        本文链接:https://www.haomeiwen.com/subject/dwvctktx.html