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);
}
}
为什么链表和那个遍历的方法要加static啊,不加就标红,问题是要实现一个数组的逆序输出,就不明白为啥要加static?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
一起随缘 2022-03-29 10:09关注因为静态方法不能调用非静态方法的属性和方法,使用时,只能将被调用的方法声明为静态的,而ListNode类之所以被声明为static的,主要是方便通过类名直接调用其属性值,不用额外new对象
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报