双向链表反转

package com.zzw.test;

/**
 * @program: HashMapTest
 * @description: 双向链表反转
 * @author: zhaozhenwei
 * @create: 2021-05-30 10:55
 **/
public class DoubleListInversion {

    public static void main(String[] args) {
        DoubleNode listInversion = createListInversion();
        printListInversion(listInversion);
        printListInversion(inversion(listInversion));

    }

    /**
     * 链表反转
     *  currentNode 当前处理的节点
     *  previous    处理的上一个节点     初始情况下为null
     *  next        要处理的下一个节点    初始情况下为第一个节点的下一个节点
     *   通过死循环进行处理,跳出判断放在循环内
     *   将当前节点的上一个节点currentNode.previous执行要处理的下一个节点next
     *   将当前节点的下一个节点currentNode.next指向上次处理的节点previous
     *   此时当前节点处理完成,进行下一个节点处理的初始化
     *      previous指向当前处理的节点currentNode
     *      判断当前节点currentNode的下一个节点next是否为null,如果为null说明当前节点currentNode是最后一个节点,跳出循环
     *          如果不为null,将下一个节点指向next.next
     * @param node
     * @return
     */
    public static DoubleNode inversion(DoubleNode node) {
        if (null == node) {
            throw new RuntimeException("反转链表起始节点不能为null");
        }
        // 当前节点
        DoubleNode currentNode = node;
        // 上个节点
        DoubleNode previous = null;
        // 下个节点
        DoubleNode next = currentNode.next;
        while (true) {
            currentNode.previous = next;
            currentNode.next = previous;
            previous = currentNode;
            if (null == next) {
                break;
            }
            currentNode = next;
            next = next.next;
        }
        return previous;
    }

    /**
     * 打印链表
     * @param node
     */
    static void printListInversion(DoubleNode node) {
        DoubleNode currentNode = node;
        while (null != currentNode) {
            System.out.println(currentNode);
            currentNode = currentNode.next;
        }
        System.out.println();
    }

    /**
     * 创建链表
     * @return
     */
    static DoubleNode createListInversion() {
        DoubleNode n1 = new DoubleNode(1);
        DoubleNode n2 = new DoubleNode(2);
        DoubleNode n3 = new DoubleNode(3);
        DoubleNode n4 = new DoubleNode(4);
        DoubleNode n5 = new DoubleNode(5);

        n1.previous = null;
        n1.next = n2;

        n2.previous = n1;
        n2.next = n3;

        n3.previous = n2;
        n3.next = n4;

        n4.previous = n3;
        n4.next = n5;

        n5.previous = n4;
        n5.next = null;

        return n1;
    }


}



class DoubleNode {
    int value;
    DoubleNode previous;
    DoubleNode next;
    public DoubleNode(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "DoubleNode{"
                + "previous: " + (null == previous ? "null" : previous.value) +
                "\tvalue=" + value
                + "\tnext:" + (null == next ? "null" : next.value) + "}";
    }
}

你可能感兴趣的:(算法,Java,java,链表,双向链表,反转)