题目内容
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路及代码实现
最简单的数组构造方法省略不写了,下面是关于迭代和递归的思路。
迭代
迭代是通过三个指针来从前往后移动,pre初始化为null,按顺序修改指针直到最后。
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = None
while head:
t = head.next
head.next = pre
pre = head
head = t
return pre
递归
其实每道题递归的算法都是比较巧妙的,思索起来也是比较耗时的。
这道题,以1->2->3->4为例,到了4的时候即4次递归后(回溯前),其实是将引用链全部打破,1234的指针全部指向null,也就是四个节点之间已经不存在指向的关系了,然后每次回溯过程会逐渐构造4->3->2->1的反向引用链。
class Solution2:
def reverseList(self, head):
if head == null or head.next == null:
return head
t = head.next
head.next = null
res = reverseList(t)
t.next = head
return res
每次函数返回值即为在一层层的递归调用中将最开始的尾节点同时也是最终的头节点返回回去。
参考
https://www.cnblogs.com/zichi/p/4738697.html