小白蛋挞 2022-03-28 20:15 采纳率: 85%
浏览 34
已结题

为什么链表和那个遍历的方法要加static啊,不加就标红,问题是要实现一个数组的逆序输出,就不明白为啥要加static?


public class Demo04 {
    public static int[] reversePrint(ListNode head){
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while (head!=null){
            stack.addLast(head.val);
            head = head.next;
        }
        int[] res = new int[stack.size()];
        for (int i = 0; i <res.length ; i++) {
            res[i] = stack.removeLast();
            System.out.println(res[i]);
        }

        return res;

    }
    private static class ListNode {
        int val;
        ListNode next;
        ListNode(int x){val = x;}
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        reversePrint(node1);
    }
}
  • 写回答

4条回答 默认 最新

  • 一起随缘 2022-03-29 10:09
    关注

    因为静态方法不能调用非静态方法的属性和方法,使用时,只能将被调用的方法声明为静态的,而ListNode类之所以被声明为static的,主要是方便通过类名直接调用其属性值,不用额外new对象

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 4月7日
  • 已采纳回答 3月30日
  • 创建了问题 3月28日