1. 程式人生 > >LeetCode 206 Reverse Linked List 解題報告

LeetCode 206 Reverse Linked List 解題報告

null python etc self 新建 一個 sin example 給定

題目要求

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]

LeetCode 206 Reverse Linked List 解題報告