一、遍历反转
核心思路:遍历原链表,从原链表的头部一个一个取节点并插入到新链表的头部
- 图示
定义一个新的变量newHead,表示新链表的头结点
遍历原链表,每次取出原链表的第一个结点,然后将它加入新链表的头部
最后将head.next指向newHead.next - 代码实现
public void reserve() {
// 如果链表为空,或者只有一个结点,则不反转
if (head.next == null || head.next.next == null) {
return;
}
// 从cur结点开始遍历
PersonNode cur = head.next;
// 定义一个新的变量tempHead, 作为新链表的头结点
PersonNode tempHead = new PersonNode(0,"","");
// next指向当前结点的下一个结点
PersonNode next;
while (cur != null) {
// 这里先保存下一个结点,然后再操作cur, 不然会导致与下一个结点的联系丢失
next= cur.next;
// 下面两行代码就是将cur加入到新链表的头部
cur.next = tempHead.next; // cur.next -> 新链表头部的后一个结点
tempHead.next = cur; // tempHead.next -> cur
cur = next; // cur后移
}
head.next = tempHead.next;
}