2012-11-03 106 views
1

我在下面的ArrayList&链表栈实现

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

先执行写入堆栈的两个实现基于接口使用ArrayList作为元素的容器,而第二实施方式使用链表。为每个底层容器分别实现或者只有一个独立于容器的堆栈实现是更好的吗?

Thnx。

回答

0

之前回答你的问题,当你使用的界面,添加“我”你的接口名称之前,如:ISTACK

当您使用界面为每个类,它实现你的注意力,当然,你必须重新 - 为每个类编写接口的方法。因为,接口没有实现那里的方法,直到接口被某些类继承,而不是提及容器的实现有所不同。

例子:

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类?

0

如果在不同情况下一个实现比其他实现更好,那么您应该同时执行这两个实现。但是,在堆栈的情况下,如果你只是push(),pop()和isEmpty(),LinkedList或者ArrayList在时间复杂性方面将不会优于另一个。所以,你可以有一个你选择的实现。

推送常量时间复杂度(),流行(),和的isEmpty():

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

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