【问题标题】:ArrayList & LinkedList Stack ImplementationArrayList 和链表栈实现
【发布时间】:2012-11-03 21:37:41
【问题描述】:

下面我写了两个基于接口的Stack实现

public interface Stack<T>{
   public void push(T t);
   public T pop();
   public boolean isEmpty();
}

第一个实现使用 ArrayList 作为元素的容器,而第二个实现使用 LinkedList。是为每个底层容器分别实现还是只有一个独立于容器的堆栈实现更好?

谢谢。

【问题讨论】:

    标签: arraylist linked-list stack containers


    【解决方案1】:

    在回答你的问题之前,当你使用接口时,在你的接口名称前加上'I',例如:IStack

    当你为每个类使用interface的时候,你要注意哪些实现,当然你必须为每个类重写interface的方法。因为,接口没有实现那里的方法,直到接口被某些类继承,更不用说容器的实现有不同。

    例子:

    class YourStackOne<T>: IStack<T>
    {
    //Container
    LinkedLink<T> ContainElement;
    
    public void push(T t){//implementation for YourStackOne..}
    public T pop(){//implementation for YourStackOne..}
    public boolean isEmpty{//implementation for YourStackOne..}
    }
    
    class YourStackTwo: IStack<int>
    {
    //Container
    ArrayList ContainElement;
    
    public void push(int t){//implementation for YourStackTwo..}
    public int pop(){//implementation for YourStackTwo..}
    public boolean isEmpty{//implementation for YourStackTwo..}
    }
    

    顺便说一句,如果你是用 .NET 编写的,为什么不使用 Stack 类呢?

    【讨论】:

      【解决方案2】:

      如果一种实现在不同情况下比另一种更好,那么您应该同时拥有两种实现。

      但是,在堆栈的情况下,如果您只有 push()、pop() 和 isEmpty(),则 LinkedList 或 ArrayList 在时间复杂度方面不会优于另一个。因此,您可以只选择一种实现方式。

      push()、pop() 和 isEmpty() 的恒定时间复杂度:

      使用 ArrayList:总是添加到列表的底部,并从底部删除。

      使用 LinkedList:始终添加到列表的前面并从前面删除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-23
        • 2013-03-17
        • 1970-01-01
        • 1970-01-01
        • 2015-05-15
        • 2015-06-17
        • 2011-07-29
        • 2017-06-30
        相关资源
        最近更新 更多