public class entry<t> {
private t value;
private entry<t> next;
public entry() {
this(null);
}
public entry(t value) {
this.value=value;
this.next=null;
}
public void setvalue(t value) {
this.value=value;
}
public void setnext(entry<t> next) {
this.next=next;
}
public t getvalue() {
return value;
}
public entry<t> getnext(){
return next;
}
}
2.节点的入栈出栈方法代码
public class link<t> {//链表实现栈,先进后出
private entry<t> headentry;
private int size=0;
public link() {
headentry =new entry<>();
}
public void pop() {//出栈
if(headentry.getnext()!=null) {
headentry.getnext().setvalue(null);
headentry.setnext(headentry.getnext().getnext());
size--;
}else {
return;
}
}
public void push(t value) {//入栈
entry<t> newentry=new entry<>(value);
if(headentry.getnext()!=null) {
newentry.setnext(headentry.getnext());
}
headentry.setnext(newentry);
size++;
}
public void show(){//打印节点
if(headentry.getnext()==null) {
return;
}
for(entry<t> p = headentry.getnext();p!=null;p=p.getnext()){
system.out.print(p.getvalue()+" ");
}
system.out.println();
}
}
3.测试类代码
public class main {
public static void main(string args[]) {
link<string> ll=new link<>();
ll.push("1");//入栈
ll.push("2");
ll.push("3");
ll.push("4");
ll.push("5");
ll.push("6");
ll.push("7");
ll.push("8");
ll.show();//打印栈内元素
ll.pop();//弹出栈顶元素
ll.show();
ll.pop();
ll.show();
}
}