- 第一种方法:对于一个长度为n的单链表head,用一个大小为n的数组arr储存从单链表从头到尾遍历的所有元素,在从arr尾到头读取元素简历一个新的单链表时间消耗O(n),空间消耗O(n)
# 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
"""
cur = head
arr = []
if cur == None or cur.next == None:
return head
else:
while cur != None:
arr.append(cur.val)
cur = cur.next
newcur = ListNode(arr[-1])
newcur2 = newcur
for i in arr[-2:-len(arr) - 1:-1]:
newcur2.next = ListNode(i)
newcur2 = newcur2.next
return newcur
2. 双指针迭代:
- 我们可以申请两个指针,第一个指针叫 pre,最初是指向 null 的。
- 第二个指针 cur 指向 head,然后不断遍历 cur。
- 每次迭代到 cur,都将 cur 的 next 指向 pre,然后 pre 和 cur 前进一位。
- 都迭代完了(cur 变成 null 了),pre 就是最后一个节点了。
# 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
"""
pre = None
cur = head
while cur != None:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
3. 递归操作
终止条件:
- 是当前节点或者下一个节点==null
- 在函数内部,改变节点的指向,也就是 head 的下一个节点指向 head 递归函数那句
head.next.next = head
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 递归终止条件是当前为空,或者下一个节点为空
if(head==None or head.next==None):
return head
# 这里的cur就是最后一个节点
cur = self.reverseList(head.next)
# 这里请配合动画演示理解
# 如果链表是 1->2->3->4->5,那么此时的cur就是5
# 而head是4,head的下一个是5,下下一个是空
# 所以head.next.next 就是5->4
head.next.next = head
# 防止链表循环,需要将head.next设置为空
head.next = None
# 每层递归函数都返回cur,也就是最后一个节点
return cur
4. 使用栈解决
因为栈是先进后出的,实现原理就是把链表节点一个个入栈,当全部入栈完之后再一个个出栈,出栈的时候在把出栈的结点串成一个新的链表。
参考:
1、 https://www.cnblogs.com/petrolero/p/9822008.html
2、https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/submissions/
3、https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/solution/3chong-jie-jue-fang-shi-zhan-shuang-lian-biao-di-g/