美文网首页
使用LinkedList编写Stack(学习java编程思想)

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

作者: 998584f56259 | 来源:发表于2016-10-24 20:03 被阅读187次

一、使用LinkedList编写Stack

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

public class Stack<T> {

  private LinkedList<T> storage = new LinkedList<T>();

  //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<String> stack = new Stack<String>();

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<String> stack = new  Stack<String>();
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<String> stack2 =
  new java.util.Stack<String>();
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编程思想)

      本文链接:https://www.haomeiwen.com/subject/pailuttx.html