LeetCode 206 Reverse Linked List 解题报告

题目要求

Reverse a singly linked list.

Example:

  Input: 1->2->3->4->5->NULL

  Output: 5->4->3->2->1->NULL

题目分析及思路

给定一个单链表,要求得到它的逆序。可以使用列表对链表结点进行保存,之后新建一个列表对链表的逆序进行保存。最后返回新建列表的第一个元素即可。

python代码

# 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:

        l = [head]

        if head == None or head.next == None:

            return head

        while l[-1].next:

            l.append(l[-1].next)

        ans = [l.pop()]

        while l:

            ans[-1].next = l.pop()

            ans.append(ans[-1].next)

        ans[-1].next = None

        return ans[0]

        

        

 

posted on 2019-03-30 09:25  锋上磬音  阅读(131)  评论(0编辑  收藏  举报