数据结构中实现栈
需要实现的方法
package cn.dataStructure2.com;
public interface Stack {
// 将 item 压入栈中
void push(int item);
// 返回栈顶元素,并且出栈
int pop();
// 返回栈顶元素,但不出栈
int peek();
// 判断这个栈是否为空栈
boolean empty();
// 返回元素个数
int size();
}
实现的具体方法过程
package cn.dataStructure2.com;
public class MyStack implements Stack {
private int top;
private int[] array;
private int Usesize;
public MyStack(int size) {
this.top = 0;
array = new int[size];
this.Usesize = 0;
}
private boolean isFull() {
return this.Usesize == array.length;
}
@Override
public void push(int item) {
if (isFull()) {
throw new RuntimeException("栈已经满了!!!!");
}
this.array[top++] = item;
this.Usesize++;
}
@Override
public int pop() {
if (empty()) {
throw new RuntimeException("栈为空!!!!!!");
}
int data = this.array[top-1];
this.top--;
this.Usesize--;
return data;
}
@Override
public int peek() {
if (empty()) {
throw new RuntimeException("栈为空!!!!!!");
}
return this.array[top-1];
}
@Override
public boolean empty() {
return this.Usesize == 0;
}
@Override
public int size() {
return this.Usesize;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
int i = 0;
while(i < this.Usesize) {
if (i == this.Usesize-1) {
sb.append(array[i]);
}else {
sb.append(array[i]+",");
}
i++;
}
sb.append("]");
return sb.toString();
}
}
测试结果
package cn.dataStructure2.com;
public class TestMyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack(10);
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println(myStack);
System.out.println(myStack.empty());
System.out.println(myStack.size());
System.out.println(myStack.pop());
System.out.println(myStack);
System.out.println(myStack.pop());
System.out.println(myStack);
myStack.peek();
System.out.println(myStack.peek());
System.out.println(myStack);
}
}