哈哈,大家平时都有使用过浏览器吧,是不是经常使用浏览器的后退功能呢?

每一次后退,浏览器都会回到上一个浏览的网页。大家有没有想过这个后退操作的基本原理呢?

没错,就是用到了栈这个数据结构。


注意点:栈一定是线性表,但是线性表却不一定是栈。从数据结构上,都是一组数据,按照有序的形式排列起来,但是线性表和栈对数据的操作是不相同的。


下面给出一个栈的接口定义

package net.itaem.list;

/**
 * 栈的接口定义
 * @author luohong QQ 846705189
 * */
public interface Stack<T> {
    
	/**
     * 判断一个栈是否为空
     * @return 如果为空,返回true;否则,返回false
     * */
	public boolean isEmpty();
	
	/**
	 * 压入栈一个元素
	 * @param e 即将要压入栈的元素
	 * */
    public void push(T e);
    
    /**
     * 弹出一个栈顶元素,并且删除该元素
     * @return 返回栈顶元素
     * */
    public T pop();
    
    /**
     * 返回栈元素长度大小
     * @return 栈元素长度大小
     * */
    public int size();
    
    /**
     * 获得栈顶元素,但是不删除该元素
     * @return 返回栈顶元素
     * */
    public T getTop();
    
    /**
     * 将栈清空
     * */
    public void clear();
    
}

下面采用数组来实现一个栈,使用数组最大的缺点就是,堆栈所能容纳的元素数量是有限个的,不能动态性增长(当然,可以通过编程实现)

package net.itaem.list.impl;

import net.itaem.list.Stack;

/**
 * 使用数组来实现的栈
 * 
 * @author luohong QQ 846705189
 * */
public class ArrayStack<T> implements Stack<T> {
    
	//使用数组来实现,注意:使用了Object数组来实现而不是T[]...因为T[]是错误的,具体内容可以参考泛型的知识
	private Object[] elements;
	//使用top指定来标识栈顶,默认为-1,代表栈为空
	private int top = -1;
	//栈的元素长度
	private int size;
	//栈的数组长度,目前这个栈是简单的,一旦初始化后,长度不可以修改
	private int length;
	
	/**
	 * 初始化栈,默认长度为10
	 * */
	public ArrayStack(){
		this.length = 10;
		elements = new Object[10];
	}
	
	/**
	 * 初始化栈,指定栈的长度
	 * */
	public ArrayStack(int length){
		this.length = length;
		elements = new Object[length];
	}
	
	@Override
	public boolean isEmpty() {
		
		return top == -1;
	}

	@Override
	public void push(T e) {
		//元素大小加1
		size++;
		//栈顶网上移动一个
		top++;
		
		if(size > length) throw new RuntimeException("栈已满");
		
		//保存元素
		elements[top] = e;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T pop() {
		T result = null;
		
		if(top >= 0){
			result = (T)elements[top];
			
			elements[top] = null;   //防止造成内存泄露
			
			size--;
			
			top--;
		}
		
		else throw new RuntimeException("栈已经为空");
		
		
		return result;
	}

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

	@SuppressWarnings("unchecked")
	@Override
	public T getTop() {
		T result = null;
		if(top != -1) {
			result = (T)elements[top];
		}
		return result;
	}

	@Override
	public void clear() {
		//清空所有的栈内元素
		while(top >= 0){
			for(int i=0; i<size; i++){
				elements[i] = null;
			}
		}
		
	}
	
	public String toString(){
		StringBuilder sb = new StringBuilder();
		if(top == -1) sb.append("null");
		else{
			for(int i=0; i<size; i++){
				sb.append(elements[i] + " ");
			}
		}
		return "the array stack size is " + size + " and the elements is " + sb.toString();
	}
	
	
	public static void main(String[] args) {
	    
		Stack<Integer> arrayStack = new ArrayStack<Integer>(10);
	    for(int i=0; i<10; i++){
	    	arrayStack.push(i);
	    }
	    
	    //如果执行这一句,就会报错
	    //arrayStack.push(10);
	    System.out.println(arrayStack);
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println("top element value is " + arrayStack.getTop());
	    System.out.println("is empty ? " + arrayStack.isEmpty());
	    System.out.println(arrayStack);
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println(arrayStack.pop());
	    System.out.println("is empty ? " + arrayStack.isEmpty());
	    
	}
    
}


输出结果

the array stack size is 10 and the elements is 0 1 2 3 4 5 6 7 8 9 
9
8
7
6
5
top element value is 4
is empty ? false
the array stack size is 5 and the elements is 0 1 2 3 4 
4
3
2
1
0
is empty ? true

哈哈,是不是很简单呢?不过不要忽视堆栈的作用哦,这也是我们经常会使用到的数据结构呢。


下面使用节点来实现堆栈,也叫做链栈,接口不变,只是内部实现改用节点类来实现。这种堆栈的优点是,没有长度限制, 可以自由添加

package net.itaem.list.impl;

import net.itaem.list.Stack;


public class LinkedStack<T> implements Stack<T> {

	/**
	 * 定义一个类来模拟节点
	 * */
	private class Node<E>{
		//节点数据
		private E data;
		//该节点的下一个节点
		private Node<E> next;
		
		/**
		 * 初始化节点
		 * */
		public Node(E data, Node<E> next){
			this.data = data;
			this.next = next;
		}
		
		public E data(){
			return data;
		}
		
		public Node<E> next(){
			return next;
		}
		
		public void setNext(Node<E> next){
			this.next = next;
		}
		
		public void setData(E data){
			this.data = data;
		}
	}
	
	//定义一个栈顶节点
	private Node<T> top;
	//保存栈的元素个数
	private int size;
	
	/**
	 * 初始化一个空的栈
	 * */
	public LinkedStack(){
	}
	
	@Override
	public boolean isEmpty() {
		return top == null;
	}

	@Override
	public void push(T e) {
		
		//压入一个新的节点元素
		Node<T> newNode = new Node<T>(e, top);
		
		top = newNode;   //将栈顶元素移动
		
		//元素长度加1
		size++;
		
	}

	@Override
	public T pop() {
		T result = null;
		
		Node<T> free = top;
		
		//这时候要将这个应用删除掉,防止内容无意识溢出
		
		if(top != null){
			result = top.data();
			top = top.next();
			//释放应用的的节点元素
			free = null;
		}else{
			throw new RuntimeException("栈已经为空");
		}
		
		//元素长度减一
		size--;
		return result;
	}

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

	@Override
	public T getTop() {
		if(top != null) return top.data();
		else return null;
	}

	@Override
	public void clear() {
		Node<T> p = top;
		
		while(p != null){
		    p.setData(null);   //释放节点
		    Node<T> q = p;
		    p = p.next();
		    q.setNext(null);
		}
		size = 0;
		top = null;
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		if(size == 0) sb.append("null");
		else{
			Node<T> p = top;
			//遍历所有节点元素
			while(p != null){
				sb.append(p.data() + " ");
				p = p.next();
			}
		}
		
		return "the stack size is " + size + " and the elements is " + sb.toString();
	}
	
	public static void main(String[] args) {
		LinkedStack<Integer> linkedStack = new LinkedStack<Integer>();
		
		for(int i=0; i<10; i++){
		    linkedStack.push(i);
		}
		
		System.out.println("before pop\n" + linkedStack);
		
		System.out.println(linkedStack.pop());
		System.out.println(linkedStack.pop());
		System.out.println(linkedStack.pop());
		System.out.println(linkedStack.pop());
		System.out.println(linkedStack.pop());
		System.out.println(linkedStack.pop());
		
		System.out.println("after pop\n" + linkedStack);
		
		linkedStack.clear();
		System.out.println("after clear\n" + linkedStack);
	}

}


输出结果为:

before pop
the stack size is 10 and the elements is 9 8 7 6 5 4 3 2 1 0 
9
8
7
6
5
4
after pop
the stack size is 4 and the elements is 3 2 1 0 
after clear
the stack size is 0 and the elements is null



总结:堆栈,不过是一种特殊的线性表,它的操作更加简单。


下面给出java.util.Stack

/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.util;

/**
 * The <code>Stack</code> class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
 * operations that allow a vector to be treated as a stack. The usual
 * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
 * method to <tt>peek</tt> at the top item on the stack, a method to test
 * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
 * the stack for an item and discover how far it is from the top.
 * <p>
 * When a stack is first created, it contains no items.
 *
 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *
 * @author  Jonathan Payne
 * @version %I%, %G%
 * @since   JDK1.0
 */
public
class Stack<E> extends Vector<E> {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly
     * the same effect as:
     * <blockquote><pre>
     * addElement(item)</pre></blockquote>
     *
     * @param   item   the item to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
	addElement(item);

	return item;
    }

    /**
     * Removes the object at the top of this stack and returns that
     * object as the value of this function.
     *
     * @return     The object at the top of this stack (the last item
     *             of the <tt>Vector</tt> object).
     * @exception  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
	E	obj;
	int	len = size();

	obj = peek();
	removeElementAt(len - 1);

	return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it
     * from the stack.
     *
     * @return     the object at the top of this stack (the last item
     *             of the <tt>Vector</tt> object).
     * @exception  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
	int	len = size();

	if (len == 0)
	    throw new EmptyStackException();
	return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     *
     * @return  <code>true</code> if and only if this stack contains
     *          no items; <code>false</code> otherwise.
     */
    public boolean empty() {
	return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack.
     * If the object <tt>o</tt> occurs as an item in this stack, this
     * method returns the distance from the top of the stack of the
     * occurrence nearest the top of the stack; the topmost item on the
     * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
     * method is used to compare <tt>o</tt> to the
     * items in this stack.
     *
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value <code>-1</code>
     *          indicates that the object is not on the stack.
     */
    public synchronized int search(Object o) {
	int i = lastIndexOf(o);

	if (i >= 0) {
	    return size() - i;
	}
	return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}

大家可以自己阅读下源代码,并不是很难

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值