當前位置:編程學習大全網 - 源碼下載 - 我要用java實現壹個棧,基本操作就是出棧入棧。請問如何實現效率比較高。

我要用java實現壹個棧,基本操作就是出棧入棧。請問如何實現效率比較高。

//這是JDK提供的棧

import java.util.Stack;

public class UsingStack {

public static void main(String[] args) {

//構造棧對象,使用類型限制,只能存儲Integer數據

Stack<Integer> s = new Stack<Integer>();

//1、2、3依次入棧

s.push(1);

s.push(2);

s.push(3);

//3、2、1依次出棧

System.out.println(s.pop());

System.out.println(s.pop());

System.out.println(s.pop());

}

}

//這是我寫的順序結構的棧

import java.util.EmptyStackException;

import java.util.Vector;

public class UsingStack{

public static void main(String[] args){

//構造棧對象,使用類型限制,只能存儲Integer數據

MyStack<Integer> s = new MyStack<Integer>();

//1、2、3依次入棧

s.push(1);

s.push(2);

s.push(3);

//3、2、1依次出棧

System.out.println(s.pop());

System.out.println(s.pop());

System.out.println(s.pop());

}

}

/**

* 棧類

* @author developer_05

* @param <T>

*/

class MyStack<T> extends Vector<T>{

/**

* 構造方法

*/

public MyStack(){

}

/**

* 入棧方法

* @param item 待入棧的元素

* @return 返回入棧的元素

*/

public T push(T item) {

addElement(item);

return item;

}

/**

* 出棧方法(同步處理)

* @return 返回出棧元素

*/

public synchronized T pop() {

T obj;

int len = size();

if (len == 0)

throw new EmptyStackException();

obj = elementAt(len - 1);

removeElementAt(len - 1);

return obj;

}

/**

* 判斷棧是否為空的方法

* @return 返回true(棧空)或false(棧非空)

*/

public boolean empty() {

return size() == 0;

}

private static final long serialVersionUID = 1L;

}

  • 上一篇:變壓器油色譜分析的儀器主要有哪些?各種儀器的參數。
  • 下一篇:怎麽確定壹個股票是否有莊家?莊家的籌碼分布情況以及莊家的成本?
  • copyright 2024編程學習大全網