反转单向链表和反转双向链表

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

反转单向链表和反转双向链表

单向链表

具体代码

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)]

双向链表

和单向链表几乎一样,注意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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值