栈和队列的基本实现(数组实现和链表实现)

来源:互联网 发布:mac解压缩软件下载 编辑:程序博客网 时间:2024/05/16 19:35

基本知识:
队列:先进先出。场景:排队购票
栈:先进后出。 场景:邮箱

以下是对栈和队列的基本操作,分别通过数组和链表进行实现

import java.util.LinkedList;/** * * @author  */class Node<T> {    Node next;    T data;    public Node() {    }    public Node(T data) {        this.data = data;    }}class myLink {    Node head;    //头插法、相当于栈、插入一个节点先进后出    public void add(Node newNode) {        newNode.next = head;        head = newNode;//        if (head == null) {//            head = newNode;//        } else {//            newNode.next = head;//            head = newNode;//        }    }    public boolean delete(Node delNode) {        if (delNode == null || delNode.next == null) {            return false;        }        Node temp = delNode.next;        delNode.data = temp.data;        delNode.next = temp.next;        return true;    }    void display() {        Node temp = head;        while (temp != null) {            System.out.println(temp.data);            temp = temp.next;        }    }}class Stack<T> {    Node top;    //进栈 //头插法、相当于栈、插入一个节点先进后出    public void push(T data) {        Node newNode = new Node(data);        newNode.next = top;        top = newNode;    }    //出栈    public T pop() {        if (top == null) {            return null;        } else {            T data = (T)top.data;            top = top.next;            return data;        }    }    public boolean isEmpty(){        return top==null;    }    //返回栈顶    public T peek() {        return (T)top.data;    }    //时间复杂度O(n^2)空间复杂度O(n)    public Stack<T> sortStack(Stack<T> unsortedStack){        Stack sortedStack=new Stack();        while(!unsortedStack.isEmpty()){            int temp=(Integer)unsortedStack.pop();            while(!sortedStack.isEmpty()&&(Integer)unsortedStack.peek()>temp){                unsortedStack.push((T) sortedStack.pop());            }            sortedStack.push(temp);        }        return sortedStack;    }}//设计一个栈,除了pop、push外,还支持min方法(时间复杂度都为1)//缺点:用了多余的空间记录每个节点的minclass StackWithMin extends Stack<NodeWithMin>{    public void  push(int data){        int newMin=Math.min(data, min());        super.push(new NodeWithMin(data, newMin));    }    public int min(){        if (this.isEmpty()) {            return Integer.MAX_VALUE;        }else{            return peek().min;        }    }}class NodeWithMin{    public int data;    public int min;    public NodeWithMin(int data, int min) {        this.data = data;        this.min = min;    }}//节省空间class StackWithMin1 extends Stack<Integer>{    Stack<Integer> temp;    public StackWithMin1() {        temp=new Stack<>();    }    public void push(int data){        if (data<=min()) {            temp.push(data);        }else{            super.push(data);        }    }    @Override    public Integer pop(){        int data=(int)super.pop();        if (data==min()) {            temp.pop();        }        return data;    }    public int min(){        if (temp.isEmpty()) {            return Integer.MAX_VALUE;        }else{            return temp.peek();        }    }}//队列class Queue {    Node first, last;    //入队、新增元素添加到了表尾部 //尾插法、先进先出    void enQueue(Object data) {        if (first == null) {            first = new Node(data);            last = first;        } else {            last.next = new Node(data);            last = last.next;        }    }    //出队    Object deQueue() {        if (first != null) {            Object data = first.data;            first = first.next;            return data;        }        return null;    }}//不同种类的动物的先进先出,为每种动物创建一个队列,然后将两者放入包裹类中abstract class Animal{    private int order;    protected String name;    public Animal(String name){        this.name=name;    }    public void setOrder(int order){        this.order=order;    }    public  int getorder(){        return order;    }    public boolean isOlderThan(Animal animal){        return this.order<animal.order;    }}class Dog extends Animal{    public Dog(String name){        super(name);    }}class Cat extends Animal{    public Cat(String name){        super(name);    }}class AnimalQueue{    LinkedList<Dog>dogs=new LinkedList<>();    LinkedList<Cat>cats=new LinkedList<>();    private int order=0;    public void enAnimalQueue(Animal animal){        animal.setOrder(order);        order++;        if (animal instanceof  Dog) {            dogs.addLast((Dog)animal);        }else if (animal instanceof Cat) {            cats.addLast((Cat)animal);        }    }    public Animal deAnimalQueue(){        //查看首部弹出最旧的值        if(dogs.size()==0){            return cats.poll();        }else if(cats.size()==0){            return dogs.poll();        }        //如果两种动物都有选择个自最老的        Dog dog=dogs.peek();        Cat cat=cats.peek();        if (dog.isOlderThan(cat)) {            return dogs.poll();        }else{            return cats.poll();        }    }}//数组实现class StackByArr<T> {    private T[] stack;    private int N;    public StackByArr(int N) {        stack = (T[]) new Object[N];    }    public boolean isEmpty() {        return N == 0;    }    public int size() {        return N;    }    private void resize(int max) {        T[] temp = (T[]) new Object[max];        System.arraycopy(stack, 0, temp, 0, max);        stack = temp;    }    public void push(T data) {        if (N == stack.length) {            resize(2 * stack.length);        }        stack[N++] = data;    }    public T pop() {        stack[N] = null;              //避免对象游离        if (N > 0 && N == stack.length / 4) {            resize(stack.length / 2);        }        return stack[--N];    }}class QueueByArr<T> {    T[] queue;    int head = 0;    int tail = 0;    int N = 0;    public QueueByArr(int size) {        this.queue = (T[]) new Object[size];    }    public boolean isEmpty() {        return head == queue.length;//线性实现,浪费了一些空间,可改进为循环实现    }    public boolean isFull() {        return tail == queue.length - 1;    }    public void enQueue(T data) {        if (isFull()) {            System.out.println("队列已满");        }        {            queue[++tail] = data;        }    }    public T deQueue() {        if (isEmpty()) {            System.out.println("队列已空");        }        return queue[head++];    }}public class Test {    public static void main(String[] args) {        System.out.println("MyStack Test:");        Stack stack = new Stack();        stack.push(1);        stack.push(2);        stack.push(3);        System.out.println(stack.pop());        stack.push(4);        System.out.println(stack.pop());        System.out.println("MyQueue Test:");        Queue queue = new Queue();        queue.enQueue('a');        queue.enQueue('b');        queue.enQueue('c');        System.out.println(queue.deQueue());        queue.enQueue('d');        System.out.println(queue.deQueue());        System.out.println("MyLink Test:");        myLink mLink = new myLink();        Node node1 = new Node(1);        Node node2 = new Node(2);        Node node3 = new Node(3);        mLink.add(node1);        mLink.add(node2);        mLink.add(node3);        mLink.display();        mLink.delete(node2);        System.out.println("删除节点之后:");        //删除节点后        mLink.display();    }}
阅读全文
0 0