欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

泛型讨论------堆栈类

程序员文章站 2024-03-15 10:48:35
...

使用泛型实现堆栈存储机制

 

例子:

 

public class Stack<T>{
	

	private static class Node<U>{
		U item;
		Node<U> next;

		Node(){
			item = null;
			next = null;
		}

		Node<U item,Node<U> next){
			this.item =item;
			this.next = next;
		}

		boolean end(){
			return item == null&&next ==null;
		}
	}

	private Note<T> top= New nOTE<T>();

	public void push(T item){
		top  = new Node<T>(item,top);
	}

	public T pop(){
		T result = top.item;
		if(!top.end()){
			top = top.next;
		return result;
	}

	public static void main(String[] args){
	
		Stack<String> s = new Stack<String>();
		for(String a:"sfdsfd fds fsdfd".split(" ")){
			s.push(a);
		}
		
		String b;
		whiel((b=s.pop()!=null){
			System.out.println(b);
		}
	}
}

 

 

本例子使用了末端哨兵来判断堆栈何时为空,这个末端哨兵是构造Stack的时候创建的,然后每次调用一次push方法,就会创建一个Node<T>对象,并将其连接到前一个Node<T>对象,当你调用pop方法时候,总是返回top.item;然后丢弃当前top所指的Node<T>,并将top转移到下一个Node<T>,除非你碰到了末端哨兵,就不在移动了,

 

 

下一个例子,:

一个持有特定对象的列表,每次在调用select方法的时候,可以随机的获取一个元素.

 

public class Random<T>{

	private ArrayList<T> store = new ArrayList<T>();
	private Random rand = new Random();

	public void add(T item){
		store.add(item);
	}

	public T select(){
		return store.get(rand.nextInt(store.size()));
	}
}