Java 实例 - 栈的实现
以下实例演示了用户如何通过创建用于插入元素的自定义函数 push() 方法和用于弹出元素的 pop() 方法来实现栈:
MyStack.java 文件
publicclassMyStack{privateintmaxSize;
privatelong[]stackArray;
privateinttop;
publicMyStack(ints){maxSize = s;
stackArray = newlong[maxSize];
top = -1;
}publicvoidpush(longj){stackArray[++top] = j;
}publiclongpop(){returnstackArray[top--];
}publiclongpeek(){returnstackArray[top];
}publicbooleanisEmpty(){return(top == -1);
}publicbooleanisFull(){return(top == maxSize - 1);
}publicstaticvoidmain(String[]args){MyStacktheStack = newMyStack(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
theStack.push(50);
while(!theStack.isEmpty()){longvalue = theStack.pop();
System.out.print(value);
System.out.print("");
}System.out.println("");
}}
以上代码运行输出结果为:
50 40 30 20 10