1.堆棧stack操作:尾進 尾出 或者叫先進后出
//1借助LinkedList 類中的方法實現棧 public class MyStack { private LinkedList<Object> li=new LinkedList<Object>(); //1構造方法 public MyStack(){ } //2出棧 public Object pop(){ if(isEmpty()){ throw new EmptyStackException(); } return li.removeFirst(); } //3進棧 public void push(Object obj){ //注意o不要0的區別,不要寫成0了 li.addFirst(obj); } //4清空 public void clear() { li.clear(); } //5判斷是否為空 public boolean isEmpty(){ return li.isEmpty(); } //6 將對象轉換成字符串 public String toString(){ return li.toString(); } //7返回棧口元素 public Object peek(){ if(isEmpty()){ throw new EmptyStackException(); } return li.peekFirst(); //注意,這里與隊列的區別 } public static void main(String[] args) { MyStack stack=new MyStack(); //進棧 stack.push("a"); stack.push("b");
stack.push("c"); //出棧 System.out.println(stack.pop()); //輸出 c //返回棧口元素 System.out.println(stack.peek()); //輸出 b } }
2.隊列queue操作:尾進 首出 或者叫先進先出,后進后出
//借助LinkedList 類中的方法實現隊列 public class MyQueue { private LinkedList<Object> li = new LinkedList<Object>(); // 1構造方法 public MyQueue() { } // 2出列 public Object get() { if (isEmpty()) { throw new EmptyStackException(); } return li.removeFirst(); } // 3進列 public void put(Object obj) { li.addLast(obj); } // 4清空 public void clear() { li.clear(); } // 5 返回隊列首元素(不刪除) public Object getTop() { if (isEmpty()) { throw new EmptyStackException(); } return li.peekLast(); //注意,這里是peeklaste而不是first } // 6將對象轉換成字符串 public String toString() { return li.toString(); } // 7判斷隊列是否為空 public boolean isEmpty() { return li.isEmpty(); } public static void main(String[] args) { MyQueue mq = new MyQueue(); // 進列 mq.put("a"); mq.put("b"); mq.put("c"); // 出列 System.out.println(mq.get()); //輸出a // 返回對首元素 System.out.println(mq.getTop()); //輸出b }