特殊的线性表-----栈---栈的插入和删除

来源:互联网 发布:举而不坚,坚而不久知乎 编辑:程序博客网 时间:2024/06/05 01:52

入栈:栈的插入运算

出栈:栈的删除运算

栈:先进后出  后进先出

出栈:栈的删除运算

下面是入栈和出栈的代码:

public class 栈的出栈和入栈 implements Stack {
String [] arr=new String[5];
int top=-1;
public void push(Object obj) throws Exception {
if(top>=arr.length-1){
throw new Exception("沾满了");
}else{top++;
arr[top]=(String) obj;
System.out.println(obj+"入站了");
}
}
@Override
public Object pop() throws Exception {
Object object=null;
if(isEmoty()){
throw new Exception("栈空了");
}else{
object=arr[top];
arr[top]=null;
top--;
System.out.println(object+"出站了");
}

return object;
}
@Override
public boolean isEmoty() {

return top==-1;
}
public static void main(String[] args) throws Exception {
栈的出栈和入栈 s=new 栈的出栈和入栈 ();
s.push("aaa");
s.push("bbb");
s.push("ccc");
s.push("ddd");
s.push("eee");
s.push("fff");
s.pop();
s.pop();
s.pop();
s.pop();
}

}

public interface Stack {
public void push(Object obj)throws Exception;
public Object pop()throws Exception;
public boolean isEmoty();
}


原创粉丝点击