JAVA实现基本的栈,主要是栈的数组实现和链表实现。
Study Note:
1 数组的栈不可以动态增长,而链表的可以
2 链表实现的栈只要内存没有满,不会出现OverStackException。
3 自定义异常类对今后的编程是很好的学习。
package com.marthevin.stack;
public class StackArrayTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// StackArray test = new StackArray(10);
// test.push(2);
// test.push(3);
// test.push(4);
// test.push(35);
// test.pop();
// System.out.println(test.getTop());
// System.out.println(test.isEmpty());
// test.printStack();
StackList test = new StackList();
test.push(91);
test.push(92);
test.push(93);
test.push(999);
System.out.println(test.getSize());
System.out.println(test.isEmpty());
System.out.println(test.pop());
System.out.println(test.getSize());
test.printStack();
}
}
class Node
{
int data;
Node link,top;
public Node(int data)
{
this.data = data;
this.link = null;
}
}
class StackList{
Node stackTop = null;
int stackSize = 0;//栈大小
public StackList()
{
this.stackTop = null;
this.stackSize = 0;
}
public boolean pop()
{
boolean flag = false;
if(this.stackTop==null)
{
new StackUnderflowException("UnderFlowException!");
}else{
stackTop = stackTop.link;
this.stackSize--;
flag = true;
}
return flag;
}
public void push(int data)
{
Node topEle = new Node(data);
topEle.link = stackTop;
stackTop = topEle;
this.stackSize++;
}
public int getSize()
{
return this.stackSize;
}
public boolean isEmpty()
{
return this.stackSize==0;
}
public void printStack()
{
Node current = stackTop;
while(current!=null)
{
System.out.print(current.data+ " ");
current = current.link;
}
}
}
class StackArray{
public int maxSize;
public int stackTop;
int[] list;
public StackArray(int maxSize)
{
this.maxSize = maxSize;
list = new int[maxSize];
for(int i=0;i<maxSize;i++)
{
list[i] = 0;
}
stackTop = 0;
}
public int getSize()
{
return stackTop;
}
public boolean isEmpty()
{
return stackTop == 0;
}
public int getTop()
{
if(this.isEmpty()) throw new StackUnderflowException("StackUnderFlowException!");
else return list[stackTop-1];
}
public boolean push(int data)//进栈操作
{
boolean flag = false;
if(stackTop>=maxSize)
{
flag = false;
throw new StackOverflowException("StackOverFlowException!");
}else
{
stackTop++;
list[stackTop-1] = data;
flag = true;
}
return flag;
}
public int pop()//出栈操作
{
int topEle = 0;
if(this.isEmpty())
throw new StackUnderflowException("StackUnderFlowException!");
else
topEle = list[stackTop-1];
list[stackTop-1]=0;
stackTop--;
return topEle;
}
public void printStack()
{
for(int i=0;i<list.length;i++)
{
System.out.print(list[i]+" ");
}
}
}