数据结构—栈(基于Java单链表实现栈push,pop)
栈是一个先入后出(First in Last Out)的有序列表,栈底固定,栈顶(top)指向新放入的元素。创建一个栈需要先定义栈的最大容量
maxSize
。每次放入新元素都创建一个新的
top
,其
value
为元素值,
next
为旧top。
class LinkedListStack{
private LinkNode top;
private int maxSize;
public int elementNum;
public LinkedListStack(int maxSize){
top = null;
this.maxSize = maxSize;
this.elementNum = 0;
}
public void setTop(LinkNode top){
this.top = top;
}
public boolean isFull(){
return elementNum==maxSize;
}
public boolean isEmpty(){
return elementNum==0;
}
public void push(int value){
if (isFull()) {
throw new RuntimeException("Stack is Full!");
}
setTop(new LinkNode(value,top));
elementNum ++;
return;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("Stack is Empty!");
}
elementNum --;
int value = top.getNo();
setTop(top.getNext());
return value;
}
public void showStack(){
if (elementNum==0){
System.out.println("Stack is Empty!");
return;
}
LinkNode temp = top;
for (int i = 0; i < elementNum; i++) {
System.out.printf("stack[%d] = %d\n",i,temp.getNo());
temp = temp.getNext();
}
return;
}
}
class LinkNode{
private int no;
private LinkNode next;
public LinkNode(int no, LinkNode next){
this.no = no;
this.next = next;
}
public LinkNode(){
}
public LinkNode(int no){
this.no = no;
this.next = null;
}
public LinkNode(LinkNode node){
this.next = node;
}
public int getNo() {
return no;
}
public LinkNode getNext(){
return next;
}
public void setNext(LinkNode next) {
this.next = next;
}
@Override
public String toString() {
return "LinkNode{" +
"no=" + no + '}';
}
}