JAVA拾遗 - 使用Java实现数列栈和链表栈

来源:互联网 发布:古筝教学软件 编辑:程序博客网 时间:2024/05/18 01:02
最近有点忙,没来得及更新博客...正好在看Alg PartI 的公开课,就发一批课堂练习凑个数吧...

抽象

栈主要有三个功能,我们可以用一个抽象类去规定他
package StackQueueBag;/** * Created by coco1 on 2016/9/12. */public abstract class AbstructStack {    public abstract boolean isEmpty();    public abstract String pop();    public abstract void push(String s);}

链表实现

链表实现就是使用节点的形式存储每一个点

package StackQueueBag;/** * Created by coco1 on 2016/9/11. *//** * all operation takes constant time in the worst case * * 16 bytes(object head) * * 8 bytes(inner class extra overhead) * * 8 bytes(reference to String) * * 8 bytes(reference to Node) * * 40 bytes per stack node  -------->40N */public class LinkedListStack extends AbstructStack{    private Node first = null;    private int count = 0;    public class Node {        String item;        Node next;        public Node() {        }        public Node(String s) {            this.item = s;            this.next = null;        }    }    public int getCount() {        return count;    }    @Override    public boolean isEmpty() {        return first == null;    }    @Override    public String pop() {        String item = first.item;        first = first.next;        count--;        return item;    }    @Override    public void push(String item) {        Node n = new Node(item);        n.next = first;        first = n;        count ++;    }}

数组实现

数组实现就是使用数组去存储每一个点

package StackQueueBag;/** * Created by coco1 on 2016/9/11. *///you have to declare the lengthpublic class ArrayListStack extends AbstructStack{    private String[] item;    private int first;    private int count;    public ArrayListStack(int n) {        item = new String[n];        first = 0;        count = n;    }    @Override    public boolean isEmpty() {        return first == 0;    }    @Override    public String pop() {        return item[first--];//        return item[--first];    }    @Override    public void push(String s) {        item[++first] = s;//        item[first++] = s;    }    /**     * 数组扩容或者减容     */    public void FixedCapacityStack(int addlength) {        String[] copy = new String[count + addlength];        System.arraycopy(item, 0, copy, 0,                Math.min(count, count + addlength));        count = count + addlength;        item = copy;    }    public static void main(String args[]) {        ArrayListStack arrayListStack = new ArrayListStack(10);        arrayListStack.push("i");        arrayListStack.push("j");        arrayListStack.push("k");        arrayListStack.push("l");        System.out.print(arrayListStack.pop());        System.out.print(arrayListStack.pop());        System.out.print(arrayListStack.pop());        System.out.print(arrayListStack.pop());        System.out.print(arrayListStack.isEmpty());    }}

注意数组实现需要添加个扩容的方法(可能会需要)

0 0
原创粉丝点击