Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
这道题拿来熟悉链表函数不错的,链表反转是基本的操作。
主要有递归和非递归两种方法。
主要是要注意递归的时候python的函数变量引用机制。
递归的时候你传一个变量过去,改变变量本身(地址)没有意义,因为上一步递归还是保存着改变前的变量(地址)
所以若想通过变量来保存最后的头结点,需要改用可变变量保存,如用list保存,来修改变量的值而非其本身。
非递归的话就很简单了,没啥要注意的,莽就是了。
之后有高效算法会更新。
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我。
欢迎大家一起套路一起刷题一起ac。
1.递归
# 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: #52 if not head:return def reverseTool(now,head): if not now.next: head[0]=now return now reverseTool(now.next,head).next=now # we can use head.next.next=head, and it must be used after reverseTool,need one more parameter return now res=[1] reverseTool(head,res) head.next=None return res[0]2.非递归
# 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: pre=None while head: temp=head.next head.next=pre pre=head head=temp return pre
