反转一个单链表。
1.示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
2.迭代方法
2.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:
# 迭代解法
cur, pre = head, None
while cur:
next= cur.next # 先记录一下当前节点的下一个节点
cur.next = pre # 1.next=None, 2.next=1, 3.next=2, 4.next=3, 5.next=4 关键点:当前节点的下个节点指向pre,完成一次cur和pre的翻转
pre = cur # 当前节点指向上一个节点,即pre右移
cur = next # 当前节点的下一个节点指向当前节点(即当前节点cur右移)
return pre
2.2 详解
第一次循环:
第一步:next = head.next
将 head.next 赋值给 next 变量,即next 指向了节点2,先将节点2 保存起来。
第二步:head.next = pre (初始pre==None)
将 pre 变量赋值给 head.next,即 此时节点1 指向了 None
第三步:pre = head
将 head 赋值给了 pre,即 pre 指向节点1,将节点1 设为“上一个节点”
第四步:head = next
将 next 赋值给 head,即 head 指向了节点2,此时节点2 设为“头节点”
第二次循环:
第一步:next = head.next
将 head.next 赋值给 next 变量,即 next 指向了节点3,先将节点3 保存起来。
第二步:head.next = pre (此时的pre已经不为None)
将 pre 赋值给 head.next,pre 在上一次循环的时候指向了节点1,那么这一步的意义就是节点2 指向了 节点1,完成1和2节点的反转。
第三步:pre = head
将 head 赋值给了 pre,即 pre 指向节点2,将节点2 设为“上一个节点”
第四步:head = next
将 next 赋值给 head,即 head 指向了节点3。此时节点3 设为“头节点”
第二次循环完毕,以此类推!第三次第四次第五次循环。
https://blog.csdn.net/gongliming_/article/details/88712221
3.递归解法
3.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:
# 递归解法
if head == None:
# 结束条件1:链表本身为空则返回空
return None
if head.next == None:
# 当前节点的下一个节点为空,则返回当前节点
return head
new_head = self.reverseList(head.next)
head.next.next = head # 5.next=4当前节点的下一个节点的下一个节点指向当前节点
head.next = None # 4.next=None 当前节点的下一个节点指向None
return new_head
3.2 详解
最内层 head.next=5,触发递归终止条件,5.next=None,所以返回节点5.
倒数第二层调用new_head = self.reverseList(4.next) 返回5,接着5.next=4, 4.next=None, 即5–>4–>None
倒数第三层 new_head = sefl.reverseList(3.next) 返回仍然是5,接着 4.next = 3, 3.next=None,即5–>4–>3–>None
倒数第四层 new_head = self.reverseList(2.next) 返回仍然是5,接着3.next = 2, 2.next=None, 即5–>4–>3–>2–>None
倒数第五层(最外层),new_head = self.reverseList(1.next) 返回仍旧是5,接着 2.next=1, 1.next =None,此时 5–>4–>3–>2–>1–>None 完成递归,返回new_head=5即指向节点5也即头节点。
https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-di-gui-by-geek-8m/