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);
}
}
因为静态方法不能调用非静态方法的属性和方法,使用时,只能将被调用的方法声明为静态的,而ListNode类之所以被声明为static的,主要是方便通过类名直接调用其属性值,不用额外new对象
加了static是静态方法,调用的时候不需要创建实例,可以直接通过类名调用
static只能访问static的方法和变量,否则new对象访问