定义类:
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
static ListNode head = null;
public static void main(String[] args) {
insert(3);
insert(2);
insert(1);
get();
get();
get();
get();
}
//进栈方法
public static void insert(int val) {
ListNode node = new ListNode(val);
//为空,让头节点为
if (head == null) {
head = node;
return;
}
//头插,放在前面
node.next = head;
head = node;
}
//出栈
public static void get() {
if (head != null) {
System.out.println(head.val);
head = head.next;
} else {
System.out.println("栈空了");
}
}
输出结果: