用链式构建的堆栈,
java 代码
- class Node{
- int element;
- Node next;
- public Node(int element){
- this(element,null);
- }
- public Node(int element, Node next){
- this.element=element;
- this.next=next;
- }
- }
-
- class Stack{
- Node header;
- public Stack(){
- header=null;
- }
- public boolean isEmpty(){
- return header==null;
- }
- public void clear(){
- header=null;
- }
- public int getTop(){
- return header.element;
- }
- public void push(int e){
- if(isEmpty()){
- header=new Node(e);
- }
- else{
- Node node=new Node(e);
- node.next=header;
- header=node;
- }
- }
- public Node pop(){
- if(!isEmpty()){
- if(header.next!=null){
- Node node=header;
- header=header.next;
- return node;
- }
- else if(header.next==null && header!=null){
- Node node=header;
- header=null;
- return node;
- }
- }
- else{
- return null;
- }
- return null;
- }
- public void printAll(){
- while(!isEmpty()){
- Node node=pop();
- System.out.print(""+node.element+" ");
- }
- }
- }
- public class ForAdd {
- public static void main(String args[]){
- Stack s=new Stack();
- for(int i=1; i<=10; i++){
- s.push(i);
- }
- s.printAll();
- }
- }
运行结果:
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) 编辑 收藏