栈的创建-----用链表实现栈

版权声明: https://blog.csdn.net/qq_39769369/article/details/83614758

设计:

1、创建Node节点类(存储链表的前节点和本节点存储的元素)

2、节点存储的是泛型数据

3、创建一个栈的接口----定义如下函数:

4、接口实现类(栈顶元素指针和链表元素计数器)

代码实现:

接口类:StackADT 



public interface StackADT <T> {
	/**
	 * 压栈
	 * @param t
	 */
	public void push(T t);
	/**
	 * 弹栈
	 * 弹出栈顶元素,并移除
	 * @return
	 * @throws EmptyCollectionException
	 */
	public T pop() throws EmptyCollectionException;
	/**
	 * 弹出栈顶元素不移除
	 * @return
	 * @throws EmptyCollectionException
	 */
	public T peek() throws EmptyCollectionException;
	/**
	 * 判断栈是否为空
	 * @return
	 */
	public boolean isEmpty();
	/**
	 * 栈当前存储的大小
	 * @return
	 */
	public int size();
	public String toString();
}

Node节点类:

public class Node<T> {
	private T element;// 当前节点存储的元素
	private Node<T> next;// 栈中的下个元素(前节点)
	/**
	 * 创建一个空节点
	 */
	public Node() {
		element=null;
		next=null;
	}
	
	/**
	 * 存储一个元素
	 * @param element
	 */
	public Node(T element) {
		super();
		this.element = element;
	}

	public Node<T> getNext() {
		return next;
	}

	public void setNext(Node<T> next) {
		this.next = next;
	}

	public T getElement() {
		return element;
	}

	public void setElement(T element) {
		this.element = element;
	}
	
}

接口实现类LinkStack:

public class LinkStack<T> implements StackADT<T>{
	//栈中存储元素的数量
	private int count;
	//指向栈顶节点
	private Node<T> top;
	
	/**
	 * 链式的实现无需担心容量限制!!
	 */
	public LinkStack() {
		count=0;
		top=null;
	}
	@Override
	public void push(T t) {
		Node<T> newNode=new  Node<T>(t);
		newNode.setNext(top);
		count++;
		top=newNode;
	}

	@Override
	public T pop() throws EmptyCollectionException {
		if(isEmpty()){
			throw new EmptyCollectionException("Stack");
		}
		T pop=((Node<T>) top).getElement();
		top=top.getNext();
		count--;
		return pop;
	}

	@Override
	public T peek() throws EmptyCollectionException {
		if(isEmpty()){
			throw new EmptyCollectionException("Stack");
		}
		return ((Node<T>) top).getElement();
	}

	@Override
	public boolean isEmpty() {
		if(size()==0){
			return true;
		}
		return false;
	}

	@Override
	public int size() {	
		return count;
	}

}

异常类EmptyCollectionException:

public class EmptyCollectionException extends Exception {

	public EmptyCollectionException(String message) {
		super("The "+message+ " is empty.");
	}

}

 测试:

/**
 * 测试类
 * @author Administrator
 *
 */
public class Main {
	public static void main(String[] args) {
		StackADT<String> stack=new LinkStack<String>();
		stack.push("1");
		stack.push("2");
		stack.push("3");
		while(!stack.isEmpty()){
			System.out.println("stack的size:"+stack.size());
			try {
				System.out.println("弹出栈顶元素:"+stack.peek());
				System.out.println("弹栈:"+stack.pop());
			} catch (EmptyCollectionException e) {
				e.printStackTrace();
			}
		}
	}
}

测试结果:

猜你喜欢

转载自blog.csdn.net/qq_39769369/article/details/83614758
今日推荐