请根据如下栈的接口定义顺序栈及链式栈public interface StackT void clear;boolean isEmpty0;boolean isFull0;void pushT element;boolean pop;T getTop;int getSize;注意:包命名为:sutIOTkongweiwei上交代码清单及运行结果截图
顺序栈的代码如下:
package sut.IOT.kongweiwei;
public class SeqStack<T> implements Stack<T> {
private Object[] stack;
private int top;
private int maxSize;
public SeqStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new Object[maxSize];
this.top = -1;
}
@Override
public void clear() {
this.top = -1;
}
@Override
public boolean isEmpty() {
return this.top == -1;
}
@Override
public boolean isFull() {
return this.top == this.maxSize - 1;
}
@Override
public void push(T element) {
if (this.isFull()) {
throw new RuntimeException("Stack is full");
}
this.stack[++this.top] = element;
}
@Override
public boolean pop() {
if (this.isEmpty()) {
return false;
}
this.top--;
return true;
}
@Override
public T getTop() {
if (this.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return (T) this.stack[this.top];
}
@Override
public int getSize() {
return this.top + 1;
}
}
链式栈的代码如下:
package sut.IOT.kongweiwei;
public class LinkedStack<T> implements Stack<T> {
private Node<T> top;
private int size;
public LinkedStack() {
this.top = null;
this.size = 0;
}
@Override
public void clear() {
this.top = null;
this.size = 0;
}
@Override
public boolean isEmpty() {
return this.top == null;
}
@Override
public boolean isFull() {
return false;
}
@Override
public void push(T element) {
Node<T> newNode = new Node<>(element);
newNode.next = this.top;
this.top = newNode;
this.size++;
}
@Override
public boolean pop() {
if (this.isEmpty()) {
return false;
}
this.top = this.top.next;
this.size--;
return true;
}
@Override
public T getTop() {
if (this.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return this.top.data;
}
@Override
public int getSize() {
return this.size;
}
private static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
this.next = null;
}
}
}
运行结果截图请见附件。
原文地址: https://www.cveoy.top/t/topic/jbhV 著作权归作者所有。请勿转载和采集!