Java泛型栈与泛型队列实现(数组与链表两种方法)

数组实现泛型栈

public class 泛型栈 {
    private Object[] data;
    private int size = 0;
    public void push(E i){
        data[size++] = i;
        if (size == data.length){
            data = Arrays.copyOf(data,data.length*2);
        }
    }
    public E pop(){
        if (size == 0){
            throw new RuntimeException("栈不能为空");
        }
        return (E) data[--size];
    }

    public 泛型栈(int length) {
        this.data = new Object[length];
    }
    public 泛型栈(){
        this.data = new Object[10];
    }
}

数组实现泛型队列(循环队列)

public class CircularQueue {
    public int[] data = new int[5];
    public int rear = 0;
    public int front = 0;

    public void push(int a){
        if(front%data.length == (rear+1)%data.length){
            System.out.println("队列满了,插入不进去");
        }else {
            System.out.println("插入了数据a"+a+"再数组下标为"+rear%data.length);
            data[rear++%data.length]=a;
        }
    }

    public int pop(){
        if (rear==front){
            System.out.println("对列已空");
            return 0;
        }
        System.out.println("取出数值是"+data[front%data.length]);
        return data[front++%data.length];
    }
    public int getLength(){
        return (rear-front+data.length)%data.length;
    }
}

链表实现泛型栈

public class LinkedStack {
    public Node head;
    public Node tail;
    public class Node{
        public E data;

        public Node next;

        public Node (E a){
            data = a;
        }
    }
    public void push(E a){
        Node node =new Node(a);
        node.next=head;
        head = node;
        System.out.println("放入了"+a);
    }

    public E pop(){
        if (head == null){
            throw new RuntimeException("栈已空");
        }
        Node node =head;
        head=head.next;
        return node.data;
    }

}

链表实现泛型队列

public class LinkedQueue {
    public class Node{
        public E data;
        public Node next;
        public Node(E a){
            data = a;
        }
    }
    public Node head;
    public Node tail;

    public void push(E a){
       if (head ==null){
           head = new Node(a);
           tail = head;
       }else {
           tail.next = new Node(a);
           tail = tail.next;
       }
        System.out.println("放入了"+a);
    }

    public E pop(){
        if (head == null){
            throw new RuntimeException("队列以空");
        }
        Node node =head;
        head = head.next;
        return node.data;
    }

}

你可能感兴趣的:(java,链表,开发语言)