反转单向链表和反转双向链表
单向链表
具体代码
public static Node reverseList(Node head){
Node pre = null;
Node next = null;
while (head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void main(String[] args) {
Node head1 = new Node(1);
head1.next = new Node(3);
head1.next.next = new Node(5);
System.out.print("原链表:");
print(head1);
System.out.println();
System.out.print("反转后链表:");
print(reverseList(head1));
}
输出结果
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t8655e3V-1611844768113)(C:\Users\18801\AppData\Roaming\Typora\typora-user-images\image-20210128223546338.png)]](https://i-blog.csdnimg.cn/blog_migrate/b58fddf865872b56a083623a512844e0.png)
双向链表
和单向链表几乎一样,注意last指针的重连即可。
public static DoubleNode reverseList(DoubleNode head){
DoubleNode pre = null;
DoubleNode next = null;
while (head != null){
next = head.next;
head.next = pre;
//last指针重连
head.last = next;
pre = head;
head = next;
}
return pre;
}

这篇博客探讨了如何反转单向和双向链表。对于单向链表,通过迭代方式更新节点的next指针实现反转。而对于双向链表,除了更新next指针,还需处理last指针的重连以完成反转操作。代码简洁明了,适用于理解链表的基本操作。
396

被折叠的 条评论
为什么被折叠?



