首页 > 解决方案 > 我手动编写Nodelist并尝试反转它为什么这里总是出现空指针异常,我试图手动创建ListNode

问题描述

第一种是手动listnode类,第二种是list reverse类,然后用main类来执行!我的想法是创建一个新的 ListNode 并将其头部传递给 ReverseList 方法,在该方法中它将反转创建的 ListNode 中的指针,然后迭代反转的列表

public class ReverseList {
    //Innerclass for a manual ListNode
    class ListNode<E> {
        ListNode<E> next;
        E val;

        public ListNode(E value) {
            val = value;
            next = null;
        }

        public ListNode(E value, ListNode<E> n) {
            val = value;
            next = n;
        }

        public void setNext(ListNode<E> n) {
            next = n;
        }
    }

    //reverse method 
    static ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode curNode = head;
        ListNode preNode = null;
        while (curNode != null) {
            ListNode nextNode = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = nextNode;
            System.out.println("This is preNode: " + preNode.val);
        }
        return preNode;
    }

    //main method for the reverse execution
    public static void main(String[] args) {
        ReverseList rl = new ReverseList();
        ReverseList.ListNode head = rl.new ListNode(1);
        for (int i = 2; i <= 5; i++) {
            head.next = rl.new ListNode(i);
            head.next = head.next.next;

        }
        ListNode ln = reverseList(head);
        //while not null it will point to next address
        while (ln.next != null) {
            System.out.println(ln.val);
            ln = ln.next;
        }
    }

}

标签: javalistreverse

解决方案


推荐阅读