随笔 - 0  文章 - 3  trackbacks - 0
<2025年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

留言簿

文章档案(50)

搜索

  •  

最新评论

用链式构建的堆栈,



java 代码




  1. class Node{   

  2.     int element;   

  3.     Node next;   

  4.     public Node(int element){   

  5.         this(element,null);   

  6.     }   

  7.     public Node(int element, Node next){   

  8.         this.element=element;   

  9.         this.next=next;   

  10.     }   

  11. }   

  12.   

  13. class Stack{   

  14.     Node header;   

  15.     public Stack(){   

  16.         header=null;   

  17.     }   

  18.     public boolean isEmpty(){   

  19.         return header==null;   

  20.     }   

  21.     public void clear(){   

  22.         header=null;   

  23.     }   

  24.     public int getTop(){   

  25.         return header.element;   

  26.     }   

  27.     public void push(int e){   

  28.         if(isEmpty()){   

  29.             header=new Node(e);   

  30.         }   

  31.         else{   

  32.             Node node=new Node(e);   

  33.             node.next=header;   

  34.             header=node;   

  35.         }   

  36.     }   

  37.     public Node pop(){   

  38.         if(!isEmpty()){   

  39.             if(header.next!=null){   

  40.                 Node node=header;   

  41.                 header=header.next;   

  42.                 return node;   

  43.             }   

  44.             else if(header.next==null && header!=null){   

  45.                 Node node=header;   

  46.                 header=null;   

  47.                 return node;   

  48.             }   

  49.         }   

  50.         else{   

  51.             return null;   

  52.         }   

  53.         return null;   

  54.     }   

  55.     public void printAll(){   

  56.         while(!isEmpty()){   

  57.             Node node=pop();   

  58.             System.out.print(""+node.element+" ");   

  59.         }   

  60.     }   

  61. }   

  62. public class ForAdd {   

  63.     public static void main(String args[]){   

  64.         Stack s=new Stack();   

  65.         for(int i=1; i<=10; i++){   

  66.             s.push(i);   

  67.         }   

  68.         s.printAll();   

  69.     }   

  70. }  



运行结果:


10 9 8 7 6 5 4 3 2 1





评论也很精彩,请点击查看精彩评论。欢迎您也添加评论。查看详细 >>





JavaEye推荐
北京:优秀公司NHNChina招聘:WEB开发,系统管理,JAVA开发, DBA
广州:急招 JAVA开发经理/系统架构师(10-15K/月)也招聘java程序员
与Hibernate之父面对面-4月19日 Gavin King上海交流研讨会
高薪工作机会 美国法国上海 15-20k/月 J2EE SA



文章来源: http://xiaozhe.javaeye.com/blog/68982
posted on 2007-04-08 10:30 xiaozhe 阅读(151) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: