力扣刷題(python)50天——第三十九天:反轉鏈表
題目描述
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
方法
由之前有關題目的解法,我也是直接將鏈表轉換爲列表,反轉後在創建新的鏈表。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
list1=[]
if not head:
return None
while head:
list1+=[head.val]
head=head.next
list1=list1[::-1]
new_head=ListNode(list1.pop(0))
o_new_head=new_head
while list1:
new_head.next=ListNode(list1.pop(0))
new_head=new_head.next
return o_new_head
執行結果
提升:
1.一個很巧的方法
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p, rev = head, None
while p:
rev, rev.next, p = p, rev, p.next
return rev
2.遞歸
主要是
n.next.next=n
有後向前遞歸
https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/