反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnhm6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1.双链表法(迭代),加入一个前置pre,一个后置head,最终返回pre
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = None
while head:
temp = head.next
head.next = pre
pre = head
head = temp
return pre
执行结果:
通过
显示详情
执行用时:44 ms, 在所有 Python3 提交中击败了62.06%的用户
内存消耗:15.4 MB, 在所有 Python3 提交中击败了78.90%的用户
递归法:(错误原因,暂时未知)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head.next==None or head:
return head
temp = head.next
reverse = reverseList(head.next)
head.next = temp.next
temp.next = head
head = temp
return reverse