public class Test {
    class Node {
        Node next;
        int data;

        protected Node(int data) {
            this.data = data;
        }
    }

    /**
     * 构建单链表
     * 
     * @param nums
     * @return
     */
    private Node create(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        Node head = new Node(nums[0]), cur = head;
        for (int i = 1; i < nums.length; i++) {
            Node node = new Node(nums[i]);
            cur.next = node;
            cur = node;
        }
        return head;
    }

    /**
     * 链表反转
     * 
     * @param head
     * @return
     */
    private Node reverse(Node head) {
        Node newHead = null, tem;
        while (head != null) {
            tem = head;
            head = head.next;
            tem.next = newHead;
            newHead = tem;
        }
        return newHead;
    }

    /**
     * 打印单链表
     * 
     * @param head
     */
    private void print(Node head) {
        Node tem = head;
        while (tem != null) {
            System.out.print(tem.data + "->");
            tem = tem.next;
        }
        System.out.println("NULL");
    }

    private void test() {
        int[] nums = new int[] { 3, 1, 0, 9, 8, 11 };
        Node root = create(nums);
        print(root);
        Node fan = reverse(root);
        print(fan);
    }

    public static void main(String[] args) {
        new Test().test();
    }
}

结果输出:

3->1->0->9->8->11->NULL
11->8->9->0->1->3->NULL
posted on 2020-05-02 21:18  玄同太子  阅读(441)  评论(0编辑  收藏  举报