搜狗笔试题之实现一个栈结构


2013-5-4号补充:

实现一个队列数据结构以及Java中队列的理解
http://blog.csdn.net/song_shi_chao/article/details/8859803 

一个面试题:关于堆栈和队列的实现
http://article.yeeyan.org/view/9225/174245


======================================================================================================

2013-4-11,搜狗笔试题,当时用ArrayList实现的,但是我总觉得不是面试官想要的实现方式,今天想起来,又查了下资料,总结如下:
 
原题是:实现一个int类型的栈结构,要求实现pop(),push()等方法。
 
 
栈的接口定义
栈接口被定义为StackADT<T>,表示作用于泛型T,在该接口的方法中,各个参数的返回值类型均使用泛型T来表述,在实现该接口时,将会用某种数据类型来替换泛型T。
public interface StackADT<T> {  
    /**
     * 往栈顶添加一个元素
     * */
    public void push(T element);  
    /**
     * 从栈顶移除一个元素,并返回该元素
     * */
    public T pop();  
    /**
     * 返回但不移除栈顶元素
     * */
    public T peek();  
    /**
     * 判断是否为空
     * */
    public boolean isEmpty();  
    /**
     * 返回栈大小
     * */
    public int size();  
    }  

java.util.Stack内置的栈结构是继承Vector实现的,代码如下:
/*
 * %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;
}

 
我实现的一个栈结构:
package com.suanfa.paixu;

/**
 * 定义一个堆栈类
 */
public class MyStack {

	// 用int数组来保存数据,根据需要可以换类型
	int[] array;

	// 定义堆栈的宽度
	int s_size;

	/**
	 * 定义一个带参数构造器
	 * @param i
	 */
	public MyStack(int i) {
		// 动态定义数组的长度
		array = new int[i];

		// 堆栈的默认宽度为0
		s_size = 0;

	}

	/**
	 * 默认构造器
	 */
	public MyStack() {
		// 默认构造器可容纳50个元素
		this(50);
	}

	public void push(int i) {
		// 压栈
		array[this.s_size] = i;

		this.s_size++;
	}

	/**
	 * 从堆栈中取元素,从栈顶开始取
	 */
	public int pop() {

		if (this.s_size != 0) {
			// 用中间变量保存栈顶的元素
			int t = array[s_size - 1];

			// 取完元素该位置设为0
			array[s_size - 1] = 0;

			// 栈的大小减1
			s_size--;

			// 返回栈顶元素
			return t;

		} else {
			System.out.println("This stack is empty");
			// 当栈为空时显示提示信息,返回0
			return 0;
		}
	}

	/**
	 * 判断栈是否为空
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		return this.s_size == 0;
	}

	/**
	 * 从栈顶取值,功能和 pop() 方法一样
	 * 
	 * @return
	 */
	public int top() {
		if (!this.isEmpty()) {
			int t = array[this.s_size - 1];
			array[this.s_size - 1] = 0;
			this.s_size--;
			return t;
		} else {
			System.out.println("This stack is empty!");
			return 0;
		}
	}

	/**
	 * 打印出堆栈中的所有元素的值,不是取出,元素依然在堆栈里
	 */
	public void printAll() {
		if (!this.isEmpty()) {
			for (int i = this.s_size - 1; i >= 0; i--) {
				System.out.println(array[i]);
			}
		}
	}

	// 下面是测试代码
	public static void main(String[] args) {
		MyStack stack = new MyStack();
		stack.push(4);
		stack.push(5);
		stack.push(6);
		stack.push(7);

		System.out.println(stack.isEmpty());

		stack.printAll();

		System.out.println("===========");
		System.out.println(stack.top());
		System.out.println(stack.top());
		System.out.println(stack.top());
		System.out.println(stack.top());
		System.out.println(stack.top());
	}

}

总体来说,这个面试题还是很棒的,很考验面试者的动手能力和思考能力,即使开始没想明白,经过思考后,也应该知道如何做了。逻辑思维能力也很重要。以后我要是当了面试官,我也考这个。
 
 
参考链接:
 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值