剑指offer第五题(从尾到头打印链表)

描述:

  将一个链表从尾到头的顺序打印出来。
代码:

package com.wzq.sword_finger_offer;

public class Sword05 {

    /**
     * 剑指offer第五题,将链表从尾到头的顺序打印出来。
     */
    public Node root;

    public void addNode(int value) {
        Node node = new Node(value);
        addNode(node);
    }

    /**
     * 迭代的方式从尾到头输出链表
     */
    public void displayFromTrail(Node node) {
        if (node == null) return;
        else {
            displayFromTrail(node.next);
            println(node.value);
        }
    }

    /**
     * 反转链表
     * @param current 当前操作的节点
     * @param pre 上一个节点
     * @param curNext 下一个节点
     */
    public void trailToHead(Node node) {
        Node current = node;
        Node pre = null;
        Node curNext = current.next;
        while (curNext != null) {
            current.next = pre;
            pre = current;
            current = curNext;
            curNext = curNext.next;
        }
        //把链表尾的数据放到翻转链表中
        current.next = pre;
        pre = current;
        root = pre;
    }

    public void println(Object object) {
        System.out.println(object);
    }

    /**
     * 构建链表
     */
    public void addNode(Node node) {
        if (root == null) {
            root = node;
        } else {
            Node current = root;
            while (current.next != null) {
                current = current.next;
            }
            current.next = node;
        }
    }

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

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

    public static void main(String... str) {
        Sword05 sword = new Sword05();
        sword.addNode(1);
        sword.addNode(2);
        sword.addNode(3);
        sword.addNode(4);
        sword.addNode(5);
        sword.addNode(6);
        sword.addNode(7);
        sword.addNode(8);

        //翻转链表
       /* sword.trailToHead(sword.root);*/

        sword.displayFromTrail(sword.root);
    }
}

你可能感兴趣的:(java,剑指offer,链表反转,链表从尾到头输出)