力扣刷题(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/