`

利用LinkedList制作一个栈

 
阅读更多
import java.util.LinkedList;

public class Stack {
	private LinkedList list = new LinkedList();
	public Stack(){	}
	
	public Object peek(){
		return list.peek();
		//取栈顶元素
	}
	
	public Object pop(){
		return list.poll();
		//出栈
	}
	
	public boolean empty(){
		return list.isEmpty();
		//判断栈是否为空
	}
	
	public void push(Object o){
		list.addFirst(o);
		//入栈
	}
	
	public int search(Object o){
		return list.indexOf(o);
		//在栈中查找元素
	}
	
	public String toString(){
		return list.toString();
	}
	
	public static void main(String[] args) {
		Stack s = new Stack();
		s.push("cc");
		s.push("dd");
		s.push("ddy");
		System.out.println(s.peek());
		System.out.println(s);
		s.pop();
		System.out.println(s);
		System.out.println(s.search("cc"));
		
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics