首先编写链表基本结构,通过链表定义栈的实现中,链表采用头插法进行创建,具体代码如下:
public class List {
int content;
List next;
public List(int content,List next){
this.content=content;
this.next=next;
}
public static List insert(List list,int context){
return new List(context,list);
}
}
接下来,定义栈结构
import java.util.Scanner;
public class Zhan {
List list;
public Zhan() {
this.list = null;
}
public void push(int context) {// 向栈中压入元素
this.list = List.insert(this.list, context);
}
public int pull() {
if (this.list == null) {
System.out.println("栈为空");
return -1;
} else {
return this.list.content;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input= new Scanner(System.in);
String number=input.nextLine();
Zhan stack=new Zhan();
while(!number.equals("end")){
stack.push(Integer.parseInt(number));
number=input.nextLine();
}
input.close();
System.out.println("弹出栈中数据");
while(stack.list!=null){
System.out.println(stack.pull());
stack.list=stack.list.next;
}
}
}