版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z740852294/article/details/77535205
数据结构-栈 JAVA语言实现
栈中的数据是先进后出的(First In Last Out, FILO)。栈只有一个出口,允许新增元素(只能在栈顶上增加)、移出元素(只能移出栈顶元素)、取得栈顶元素等操作。
目录
基于数组实现栈
public class ArrayStack {
private int[] array;
//栈顶位置
private int top = -1;
// 容量
private int capacity;
public ArrayStack(int[] array, int capacity) {
this.array = array;
top = array.length - 1;
this.capacity = capacity;
}
/**
* 是否为空
*
* @return
*/
private boolean isEmpty() {
if (top == -1) {
return true;
} else {
return false;
}
}
/**
* 是否栈满
*
* @return
*/
private boolean isFull() {
if (top == capacity - 1) {
return true;
} else {
return false;
}
}
/**
* 将data插入栈
*
* @param data 插入数据
*/
private void push(int data) {
if (isFull()) {
return;
} else {
array[++top] = data;
}
}
/**
* 出栈
*
* @return 如果为空,返回0 否则返回出栈的data
*/
private int pop() {
if (isEmpty()) {
return 0;
} else {
return array[top--];
}
}
}
局限性:栈的空间必须先申明
基于链表实现栈
public class ListStack {
private ListNode headNode;
public ListStack(){
this.headNode = new ListNode(1,null);
}
/**
* 入栈
* @param data
*/
private void push(int data){
if (headNode == null){
headNode.setData(data);
}else {
ListNode newNode = new ListNode(data,null);
newNode.setNext(headNode);
headNode = newNode;
}
}
/**
* 出栈
* @return 出栈的数据
*/
public int pop(){
int data = headNode.getData();
headNode = headNode.getNext();
return data;
}
public boolean isEmpty(){
return headNode == null;
}
}
Java Stack 类
java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的,而非链表。当然,我们也可以将LinkedList当作栈来使用!
除了由Vector定义的所有方法,自己也定义了一些方法:
- boolean empty()
测试堆栈是否为空。 - Object peek( )
查看堆栈顶部的对象,但不从堆栈中移除它。 - Object pop( )
移除堆栈顶部的对象,并作为此函数的值返回该对象。 - Object push(Object element)
把项压入堆栈顶部。 - int search(Object element)
返回对象在堆栈中的位置,以 1 为基数。
实例代码:
public class StackDemo {
private void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
private void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
StackDemo demo = new StackDemo();
Stack st = new Stack();
System.out.println("stack: " + st);
demo.showpush(st, 44);
demo.showpush(st, 22);
demo.showpush(st, 33);
demo.showpop(st);
demo.showpop(st);
demo.showpop(st);
try {
demo.showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
运行结果: