📄 ppstack.java
字号:
/*1. 有一个接口IStack,定义了一个栈的操作,请使用数组和链表两种实现方法把该接口实现,并做测试类
测试它们。*/
interface IStack {
static final int Max_Stack_Len = 100; //定义了stack的最大长度,最多存100个元素
void push(Object o);
Object pop();
}
class ArrayStack implements IStack {
Object[] elements;
int top;
ArrayStack()
{
elements = new Object[Max_Stack_Len];
top = -1; //表达栈内无元素,当压一个元素进来的时候,
}
ArrayStack(int size)
{
if (size > Max_Stack_Len)
{
System.out.println("you try to create a too large stack. failed");
System.exit(0);
}
elements = new Object[size];
top = -1;
}
public void push(Object o)
{
if(top==elements.length -1)
System.out.println("stack is full. failed");
elements[++top]=o;//把压栈工作完成
}
public Object pop()
{
if(top<0)
System.out.println("stack is empty. failed");
return elements[top--];
//完成弹栈工作,如果栈空,弹一个null
}
}
//这里是完成一个链表形的栈
//先定义链表节点
class LinkElement {
Object o;
LinkElement next;
LinkElement(Object o)
{
this.o = o;
this.next = null;
}
}
class LinkStack implements IStack {
LinkElement top; //这里栈的顶用这个top表达
int numOfElements; //记录栈中存的元素个数
LinkStack()
{
top = null;
numOfElements = 0;
}
public void push(Object o)
{
LinkElement l = new LinkElement(o);
//下面你把新节点插入在top前面,然后让top指定新节点为栈顶
l.o=o;
l.next=top;
top=l;
}
public Object pop()
{
if(top==null)
System.out.println("stack is empty. failed");
{
Object o=top.o;
top=top.next;
return o;
}
}
}
public class PPStack{
public static void main(String[] args) {
IStack m=new ArrayStack();
IStack n=new LinkStack();
m.push(new Integer(1));
n.push(new Integer(2));
m.push(new Integer(3));
n.push(new Integer(4));
m.push(new Integer(5));
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(n.pop());
System.out.println(n.pop());
// TODO 自动生成方法存根
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -