class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""
反转链表:定义前节点和当前节点
:param head:
:return:
"""
pre, curr = None, head
while curr is not None:
next = curr.next
curr.next = pre
pre = curr
curr = next
return pre
2.解法二
构造一个新链表,从旧链表 依次拿到每个节点,创建新节点添加至新链表头部,完成后新链表即是倒序的
评价:简单直白,就是得新创建节点对象
java复制代码
// 创建新节点
public ListNode reverseList(ListNode o1) {
//创建新的链表空节点
ListNode n1 = null;
//设置临时节点,把o1指向p
ListNode p = o1;
while (p != null) {
//创建节点,新节点的下一个节点是新链表,并重置新链表的头部
n1 = new ListNode(p.val, n1);
//移动旧链表的位置
p = p.next;
}
//因为重置了n1,直接返回n1
return n1;
}
n 1 o 1 1 → o 2 2 → 3 → 4 → 5 → n u l l \frac{n1 \ o1}{1} \rightarrow \frac{o2}{2} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 1n1 o1→2o2→3→4→5→null
o 2 2 → n 1 o 1 1 → 3 → 4 → 5 → n u l l \frac{o2}{2} \rightarrow \frac{n1 \ o1}{1} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 2o2→1n1 o1→3→4→5→null
n1 指向 o2
n 1 o 2 2 → o 1 1 → 3 → 4 → 5 → n u l l \frac{n1 \ o2}{2} \rightarrow \frac{o1}{1} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 2n1 o2→1o1→3→4→5→null
o2 指向 o1 的下一个节点,即
n 1 2 → o 1 1 → o 2 3 → 4 → 5 → n u l l \frac{n1}{2} \rightarrow \frac{o1}{1} \rightarrow \frac{o2}{3} \rightarrow 4 \rightarrow 5 \rightarrow null 2n1→1o1→3o2→4→5→null
n 1 n u l l \frac{n1}{null} nulln1, o 1 1 → 2 → 3 → 4 → 5 → n u l l \frac{o1}{1} \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 1o1→2→3→4→5→null
开始循环,o2 指向原链表次节点
n 1 n u l l \frac{n1}{null} nulln1, o 1 1 → o 2 2 → 3 → 4 → 5 → n u l l \frac{o1}{1} \rightarrow \frac{o2}{2} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 1o1→2o2→3→4→5→null
搬移
o 1 1 → n 1 n u l l \frac{o1}{1} \rightarrow \frac{n1}{null} 1o1→nulln1 , o 2 2 → 3 → 4 → 5 → n u l l \frac{o2}{2} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 2o2→3→4→5→null
指针复位
n 1 1 → n u l l \frac{n1}{1} \rightarrow null 1n1→null , o 1 o 2 2 → 3 → 4 → 5 → n u l l \frac{o1 \ o2}{2} \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow null 2o1 o2→3→4→5→null