list实现栈以及队列操作

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
  
    }  
原文地址:https://www.cnblogs.com/Andrew520/p/8884399.html