【算法07】反转链表

目录

导读

链表

特点

单链表和双链表的定义

单向链表

Node结点

反转单向链表

测试函数

双向链表

Node结点

反转双向链表

测试代码


导读

本文主体为单项链表和双向链表的反转以及简单的测试,以便于理解链表相关的算法题目。

链表

特点

  • 便于增删数据,不便于寻址
  • 在内存中属于跳转结构

单链表和双链表的定义

单链表: 值,一条next指针

双链表:值,一条last指针,一条next指针

单向链表

Node结点

public static class Node {
    public int value;
    public Node next;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        ArrayList<Integer> nums = new ArrayList<>();
        Node node = this;
        while (node != null) {
            nums.add(node.value);
            node = node.next;
        }
        return nums.toString();
    }
}

反转单向链表

public static Node reverseLinkedList(Node head) {
    Node next = null;
    Node pre = null;
    while (head != null) {
        next = head.next;
        head.next = pre;
        pre = head;
        head = next;
    }
    return pre;
}

测试函数

public static void main(String[] args) {
    Node node = new Node(1);
    node.next = new Node(2);
    node.next.next = new Node(3);
    node = reverseLinkedList(node);
    System.out.println(node);
}

输出结果如下:

[3, 2, 1]

双向链表

Node结点

public static class DoubleList {
    public int value;
    public DoubleList next;
    public DoubleList last;

    public DoubleList(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        ArrayList<Integer> nums = new ArrayList<>();
        DoubleList node = this;
        while (node != null) {
            nums.add(node.value);
            node = node.next;
        }
        return nums.toString();
    }
}

反转双向链表

public static DoubleList reverseDoubleList(DoubleList head) {
    DoubleList next;
    DoubleList pre = null;
    while (head != null) {
        next = head.next;
        head.next = pre;
        // 注意和单项链表不一样的地方只有这一行,其他都基本一样
        head.last = next;
        pre = head;
        head = next;
    }
    return pre;
}

测试代码

public static void main(String[] args) {
    DoubleList node1 = new DoubleList(1);
    node1.next = new DoubleList(2);
    node1.next.last = node1;
    node1.next.next = new DoubleList(3);
    node1.next.next.last = node1.next;
    System.out.println("reverseDoubleList(node1) = " + reverseDoubleList(node1));
}

输出结果如下:

reverseDoubleList(node1) = [3, 2, 1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ziop-三月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值