使用LinkedList编写Stack(学习java编程思想)

一、使用LinkedList编写Stack

//使用LinkedList编写一个Stack栈
import java.util.LinkedList;

public class Stack {

  private LinkedList storage = new LinkedList();

  //addFirst:在LinkedList的头部插入一个元素
  public void push(T v) { storage.addFirst(v); }
  public T peek() { return storage.getFirst(); }
  public T pop() { return storage.removeFirst(); }
  public boolean empty() { return storage.isEmpty(); }
  public String toString() { return storage.toString(); }
}  

二、测试

public class StackTest {
public static void main(String[] args) {
  
Stack stack = new Stack();

for(String s : "My dog has fleas".split(" "))
  stack.push(s);
while(!stack.empty())
  System.out.print(stack.pop() + " ");
}
} /* Output:
fleas has dog My
*///:~

三、比较

尽管我们看不出两个Stack的差别,但是使用LinkedList编写的Stack拥有更好的性能,所以推荐使用LinkedList编写的Stack。

public class StackCollision {
public static void main(String[] args) {
  
 Stack stack = new  Stack();
for(String s : "My dog has fleas".split(" "))
  stack.push(s);

while(!stack.empty())
  System.out.print(stack.pop() + " ");

System.out.println();
java.util.Stack stack2 =
  new java.util.Stack();
for(String s : "My dog has fleas".split(" "))
  stack2.push(s);

while(!stack2.empty())
  System.out.print(stack2.pop() + " ");
}
} /* Output:
fleas has dog My
fleas has dog My
*///:~

你可能感兴趣的:(使用LinkedList编写Stack(学习java编程思想))