栈:后进先出;最后一个放入堆栈中的物体总是被最先拿出来。
使用链表来模拟栈的入栈出栈操作。
1.节点类代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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.节点的入栈出栈方法代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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.测试类代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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(); } } |
4.测试结果
以上所述是小编给大家介绍的java 使用链表来模拟栈的入栈出栈操作详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
原文链接:https://HdhCmsTestcnblogs测试数据/zunzunzunshen/p/10301415.html
查看更多关于java使用链表来模拟栈的入栈出栈操作实例代码的详细内容...