`

栈 java实现

阅读更多
package com.shine.stack;
/*
* 栈的接口
*/
public interface SStack<T> {
boolean isEmpty();
void push(T x);
T pop();
T get();
}



package com.shine.stack;
/*
* 顺序栈类
*/
public class SeqStack<T> implements SStack<T> {
    private Object element[];
    private int top;
    public SeqStack(int size){//构造容量为size的空栈
    this.element = new Object[Math.abs(size)];
    this.top = -1;
    }
    public SeqStack(){
    this(64);
    }
@Override
public boolean isEmpty() {
return this.top==-1;
}
@Override
public void push(T x) {//入栈操作
if(x==null)
return;
if(this.top==this.element.length-1){//若栈满,需要扩充栈的容量
Object[] temp = this.element;
this.element = new Object[temp.length*2];
for(int i=0;i<this.element.length;i++){
this.element[i] = temp[i];
}
this.top++;
this.element[this.top] = x;
}

}
@Override
public T pop() {//出栈操作
return this.top==-1?null:(T)element[top--];
}

@Override
public T get() {//获取栈顶元素
return this.top==-1?null:(T)element[top];
}
}



package com.shine.stack;
import com.shine.linearList.Node;
/*
* 链式栈
*/
public class LinkedStack<T> implements SStack<T>{
    private Node<T> top;
    public LinkedStack(){
    this.top = null;
    }
@Override
public boolean isEmpty() {
return this.top==null;
}

@Override
public void push(T x) {
if(x!=null)
this.top = new Node(x,this.top);
}
@Override
public T pop() {
if(this.top == null)
return null;
T temp = this.top.data;
this.top = this.top.next;
return temp;
}
@Override
public T get() {
return this.top==null?null:this.top.data;
}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics