用java写一个栈,非java自带的栈

来源:互联网 发布:idn域名 编辑:程序博客网 时间:2024/06/05 02:03

package com.test.stack;
//栈:后进先出
public class StackX {

 private int[] stackArray;
 private int maxSize;
 private int top;
 
 public StackX(int s)
 {
  maxSize = s;
  stackArray = new int[maxSize];
  top = -1;
 }
 
 public void push(int i)
 {
  stackArray[++top] = i;
 }
 
 public int pop(){
  return stackArray[top--];
 }
 
 public boolean isEmpty()
 {
  return (top == -1);
 }
 
 public int peek()
 {
  return stackArray[top];
 }
 
 public boolean isFull()
 {
  return (top == maxSize - 1);
 }
}

 

 

import java.util.Stack;

public class StackMain {

 public static void main(String[] args)
 {
  StackX s = new StackX(10);
  s.push(20);
  s.push(30);
  s.push(40);
  s.push(50);
  s.push(60);
  
  while(!s.isEmpty())
  {
   System.out.println(s.pop());
  }
  
  Stack<Integer> a = new Stack<Integer>();
  a.push(10);
  a.push(11);
  a.push(12);
  a.push(13);
  
  while(!a.isEmpty())
  {
   System.out.println(a.pop());
  }
 }
}

输出结果为:

20
13
12
11
10