实现一个双向链表的倒置功能

小编 2026-06-12 阅读:662 评论:0
题目要求:实现一个双向链表的倒置功能(1->2->3 变成 3->2->1) 要求成果物:代码、测试用例(单元测试) Tips:认真审题,请勿直接使用JDK的LinkedList。...

题目要求:实现一个双向链表的倒置功能(1->2->3 变成 3->2->1)
要求成果物:代码、测试用例(单元测试)
Tips:认真审题,请勿直接使用JDK的LinkedList。

双向链表类代码:

public class DoubleLinkedList<E> {

    transient Node<E> first; //头节点
    transient Node<E> last; //尾节点
    transient int size = 0; //节点个数

    public DoubleLinkedList() {
    }

    /**
     * 判断是否为空
     *
     * @return true 为空, false 不为空
     */
    public boolean isEmpty() {
        return 0 == size;
    }

    /**
     * 获取表元素个数
     *
     * @return 表链元素个数
     */
    public int size() {
        return size;
    }

    /**
     * 反序排列列表中的值
     */
    public void reverse() {
        if (isEmpty()) {
            return;
        }
        // 表的头节点与尾节点互换位置
        Node<E> temp = first;
        first = last;
        last = temp;

        // 从表头按序遍历 更每个新节点的前后节点互换
        Node<E> n = first;
        while (n != null) {
            temp = n.next;
            n.next = n.per;
            n.per = temp;
            n = n.next;
        }
    }

    /**
     * 根据索引获取元素
     *
     * @param index 元素
     * @return
     */
    public E get(int index) {
        checkIndex(index);
        return getNode(index).item;
    }

    /**
     * 将元素追加到列表的末尾
     *
     * @param item 元素
     */
    public void add(E item) {
        Node<E> l = last;
        Node<E> newNode = new Node(l, item, null);
        last = newNode;
        if (l == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
        size++;
    }

    /**
     * 根据索引获取节点
     *
     * @param index 索引
     * @return 节点
     */
    private Node<E> getNode(int index) {
        if (index < (size >> 2)) { //如果索引在列表前面 正序遍历
            Node<E> node = first;
            for (int i = 0; i < index; i++) {
                node = node.next;
            }
            return node;
        } else { //否则倒叙遍历
            Node<E> node = last;
            for (int i = size - 1; i > index; i--) {
                node = node.per;
            }
            return node;
        }
    }

    /**
     * 检查索引值
     *
     * @param index 索引
     */
    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
    }

    /**
     * 节点元素
     *
     * @param <E>
     */
    private class Node<E> {
        E item;//元素的值
        Node per;// 前一个结点
        Node next;// 后一个结点

        public Node(Node per, E item, Node next) {
            this.item = item;
            this.per = per;
            this.next = next;
        }

        public String toString() {
            return item + \"\";
        }
    }

    /**
     * 自定义个一个列表迭代器
     *
     * @return
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {

        int cursor = 0;
        int lastRet = -1;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            try {
                E next = get(cursor);
                lastRet = cursor++;
                return next;
            } catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (-1 == lastRet) {
                throw new IllegalStateException();
            }
            throw new RuntimeException(\"remove is denied\");
        }
    }
}

下面在创建一个测试用例:

public class DoubleLinkedListTest {

    /**
     * 链表打印
     *
     * @param list
     */
    public static void printDoubleLinkedList(DoubleLinkedList<Integer> list) {
        StringBuffer sb = new StringBuffer();
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()) {
            sb.append(it.next());
            if(it.hasNext()) {
                sb.append(\"->\");
            }
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        DoubleLinkedList<Integer> list = new DoubleLinkedList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);

        System.out.println(\"链表倒置前:\");
        printDoubleLinkedList(list);

        list.reverse();

        System.out.println(\"链表倒置后:\");
        printDoubleLinkedList(list);
    }
}

测试结果:

C:\\Java\\jdk1.8.0_171\\bin\\java.exe ...
链表倒置前:
1->2->3
链表倒置后:
3->2->1

Process finished with exit code 0

版权声明

本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。

上一篇:数组的操作(2) 下一篇:判断数据类型
热门文章
  • 机房智能化温湿度解决方式之POE供电以太网温湿度传感器

    机房智能化温湿度解决方式之POE供电以太网温湿度传感器
    机房智能化温湿度解决方式之POE供电以太网温湿度传感器 北京盈创力和电子科技有限公司 智能型TCP网口温湿度记录仪 北京IP网络温湿度记录仪厂家,北京盈创力和 北京智能型TCP网口温湿度记录仪IP网络温湿度记录仪是一种新型的基于TCP/IP协议双绞线以太网标准温湿度采集模块,利用它可以实现现场温度值、相对湿度值的采集,同时利用其自身的RJ45通信接口可以方便地和机房监控主机或交换机集线器进行联网。 工作于-40℃~85℃工业级带...
  • Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering

    Sequential Monte Carlo Methods (SMC) 序列蒙特卡洛/粒子滤波/Bootstrap Filtering
    Problem Statement 我们考虑一个具有马尔可夫性质、非线性、非高斯的状态空间模型(State Space Model):对于一个时间序列上的观测结果{yt,t∈N}\\{ y_t , t \\in N \\}{yt​,t∈N},我们认为每个观测结果yty_tyt​的生成依赖于一个无法直接观察的隐变量xt∈{xt,t∈N}x_t \\in \\{x_t , t \\in N \\}xt​∈{xt​,t∈N},即:p(...
  • HTTP状态保持的原理

    HTTP状态保持的原理
    a)在用户登录之后,浏览器返回响应的时候会在响应中添加上cookieb)浏览器接收到cookie之后会自动保存c)当用户再次请求同一服务器中的其他网页的时候,浏览器会自动带上之前保存的cookied)服务接收到请求之后可以请 request 对象中取到cookie 判断当前用户是否登录  Http是无状态的,就是连接时数据互通,关闭后...
  • Hive 系统函数及示例

    Hive 系统函数及示例
    查看所有系统函数 show functions; 函数分类 内置函数【系统函数】 数学函数: floor、round、ceil、cos、log2等 字符串函数: length、reverse、trim、lower、get_json_object、repeat等 收集函数: size 转换函数: cast 日期函数: year、month、datediff、date、date_add等 条件函数: coalesce、case…w...
  • CSRF的原理和防范措施

    CSRF的原理和防范措施
    a)攻击原理:i.用户C访问正常网站A时进行登录,浏览器保存A的cookieii.用户C再访问攻击网站B,网站B上有某个隐藏的链接或者图片标签会自动请求网站A的URL地址,例如表单提交,传指定的参数iii.而攻击网站B在访问网站A的时候,浏览器会自动带上网站A的cookieiv.所以网站A在接收到请求之后可判断当前用户是登录状态,所以...
标签列表