欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java code,

来源: javaer 分享于  点击 46597 次 点评:190

java code,


实现栈以及队列

public class Node{ 
   private Object value;
   private Node next;
}

public class Stack{
  Node top;
  
  public void push(Object value){
     Node node = new Node();
	 node.setValue(value);
	 if(top!=null){
		node.next = top.next;
	 }     
	 top.next = node;
  }
  
  public Object pop(){
    if(top.value!=null){
	   Object value = top.value;
       top = top.next;	   
	   return value;
	}
    return null;
  }
}

public class Queue{
   Node tail;
   Node top;
   
   public void Queue(){
     tail = top;
	 tail = null;
   }

   public void push(Object value){
     Node node = new Node(value);
     if(tail==null){
		top = node;
		tail = node;
     } else{
	    tail.next = node;
		tail = node;	
     }	 	 
   }
   
   public Object pop(){      //顺序很重要,分头尾指针,出队列分三种情况
     if(top==null){
		return null;
	 }
	 Object value= top.value;
     if(top!=tail){
		 top = top.next;		 
	 }else{
         top = null;
     }	   
	 return value;
   }
}

单例

1. 内部类

public class Singleton {  
    private static class SingletonHolder {  
    private static final Singleton INSTANCE = new Singleton();  
    }  
  
    public static final Singleton getInstance() {  
    return SingletonHolder.INSTANCE;  
    }  
}  

2.直接生成

public class Singleton {  
    private static Singleton instance = new Singleton();  
  
    public static Singleton getInstance() {  
    return instance;  
    }  
} 

3.双重判断

public class Singleton {  
    private volatile static Singleton singleton;  
  
    public static Singleton getSingleton() {  
    if (singleton == null) {  
        synchronized (Singleton.class) {  
        if (singleton == null) {  
            singleton = new Singleton();  
        }  
        }  
    }  
    return singleton;  
    }  
}  



相关文章

    暂无相关文章
相关栏目:

用户点评