java code

来源:互联网 发布:炫浪网络社区怎么了 编辑:程序博客网 时间:2024/06/05 03:25

实现栈以及队列

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;      }  }  



0 0