直接使用stack类:
Stack<String> stack=new Stack();
stack.add("Bob");
stack.add("Lily");
stack.add("Smith");
while (stack.size()>0){
System.out.println(stack.pop());
数组:
class ArrayStack{
private int maxSize;
private int[] stack;//栈空间
private int top=-1;
public ArrayStack(int maxSize){
this.maxSize=maxSize;
stack=new int[maxSize];
}
public boolean isFull(){
return top==maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
if (isFull()){
System.out.println("Stack is full");
return;
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
if (isEmpty())
throw new RuntimeException("Stack is empty");
int value=stack[top];
top--;
return value;
}
public void show(){
if(isEmpty()){
System.out.println("Stack is empty");
return;
}
for (int i=top;i>=0;i--)
System.out.println(stack[i]);
}
}
链表:
注意:用temp变量时,不能直接用temp=null or temp=new Node()的方式来修改结点,而要用指针的方式temp.next==……来修改结点。
class ListStack{
Node first=null;
int maxSize;//记录栈的最大数据量
public ListStack(int maxSize){
this.maxSize=maxSize;
}
//栈的有效数据个数
public int getLength(){
int count=0;
Node temp=first;
while (temp!=null){
count++;
temp=temp.getNext();
}
return count;
}
public boolean isFull(){
return maxSize==getLength();
}
public boolean isEmpty(){
return getLength()==0;
}
//入栈
public void push(int value){
if (isFull()){
System.out.println("栈已满,无法添加");
return;
}
if (first==null) {//头结点
first = new Node(value);//不能写temp=new Node(value)
return;
}
Node temp=first;
while (temp.getNext()!=null)
temp=temp.getNext();
temp.setNext(new Node(value));
}
//出栈
public void pop(){
if (isEmpty()){
System.out.println("栈空,无法删除");
return;
}
Node temp=first;
while (temp.getNext().getNext()!=null)
temp=temp.getNext();
temp.setNext(null);//只能用next的方式,不能写temp=null;
}
//遍历
public void show(){
if (isEmpty()){
System.out.println("Stack is empty");
return;
}
Node temp=first;
while (temp!=null){
System.out.println(temp);
temp=temp.getNext();
}
}
}
class Node{
private int no;
private Node next;
public Node(int no){
this.no= no;
}
public int getNo() {
return no;
}
public Node getNext() {
return next;
}
public void setNo(int no) {
this.no = no;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}