现在的位置: 首页 > 综合 > 正文

我遇到的java 笔试题: 定义stack 接口类

2018年05月10日 ⁄ 综合 ⁄ 共 1290字 ⁄ 字号 评论关闭

//定义栈接口类
interface Stack_Interface<T>
{
public T pop();

public void push(T item);

public T gettop();

public boolean isEmpty();

public int getsize();
}

class stackList<T> implements Stack_Interface<T>
{
int capacity;
int size;
Object[] stacklist;

public stackList(int capacity)
{
this.capacity=capacity;
this.size=0;
this.stacklist=new Object[capacity];
}

public T pop()
{
T member=(T)this.stacklist[size-1];
this.stacklist[size-1]=null;
size--;
return member;
}

public void push(T item)
{
if(this.size<this.capacity)
{
this.stacklist[size]=item;
this.size++;
}
else
{
System.out.println("out of stacklist");
}
}

public T gettop()
{
return (T)this.stacklist[size-1];
}

public boolean isEmpty()
{
return size==0;
}

public int getsize()
{
return this.size;
}

}

public class stack
{
public static void main(String[] args) 
{
stackList<Integer> stacklist=new stackList<Integer>(3);
System.out.println("size is:" + stacklist.getsize());
System.out.println("isEmpty?:" + stacklist.isEmpty());
System.out.println("push");
stacklist.push(1);
System.out.println("size is:" + stacklist.getsize());
System.out.println("push");
stacklist.push(2);
stacklist.push(3);
System.out.println("size is:" + stacklist.getsize());
stacklist.push(4);
System.out.println("top is:" + stacklist.gettop());
System.out.println("isEmpty?:" + stacklist.isEmpty());

}

}

output:

size is:0
isEmpty?:true
push
size is:1
push
size is:3
out of stacklist
top is:3
isEmpty?:false

抱歉!评论已关闭.