剑指 Offer 09. 用两个栈实现队列(简单),顺便再学习一下LinkedList

直接上题,下面有转载的解析,大家仔细阅读

以下为转载内容

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/comments/258737

(编辑过)2020-02-27

使用java的同学请注意,如果你使用Stack的方式来做这道题,会造成速度较慢; 原因的话是Stack继承了Vector接口,而Vector底层是一个Object[]数组,那么就要考虑空间扩容和移位的问题了。 可以使用LinkedList来做Stack的容器,因为LinkedList实现了Deque接口,所以Stack能做的事LinkedList都能做,其本身结构是个双向链表,扩容消耗少。 但是我的意思不是像100%代码那样直接使用一个LinkedList当做队列,那确实是快,但是不符题意。 贴上代码,这样的优化之后,效率提高了40%,超过97%。

class CQueue {
    LinkedList<Integer> stack1;
	LinkedList<Integer> stack2;

	public CQueue() {
		stack1 = new LinkedList<>();
		stack2 = new LinkedList<>();
	}

	public void appendTail(int value) {
		stack1.add(value);
	}

	public int deleteHead() {
		if (stack2.isEmpty()) {
			if (stack1.isEmpty()) return -1;
			while (!stack1.isEmpty()) {
				stack2.add(stack1.pop());
			}
			return stack2.pop();
		} else return stack2.pop();
	}
}

问:可是linkedlist没有pop方法啊 不是要用removeLast吗

答: LinkedList实现了pop方法的,javadoc中的原文:

/** * Pops an element from the stack represented by this list.

In other

* words, removes and returns the first element of this list.

* * <p>This method is equivalent to {@link #removeFirst()}.

* * @return the element at the front of this list (which is the top * of the stack represented by this list)

* @throws NoSuchElementException if this list is empty * @since 1.6

 

问:小弱问一下,AbstractList<-AbstractSequentialList<-LinkedList,AbstractList<-Vector<-Stack,stack和linkedlist不是都从AbstractList继承来的吗?

 很好,终于有人来问这样的问题了。LinkedList直接继承于AbstractSequentialList,也就是直接继承于顺序表抽象类,这个有序表抽象类继承于列表抽象类(AbstractList)。 AbstractList提供了基本的列表操作,其的doc中写道:For sequential access data (such as a linked list),AbstractSequentialList should be used in preference to this class. 也就是对于顺序表,需要优先继承于顺序表抽象类而非直接使用列表抽象类。 这个是在架构或者说是在思想层面上的解释,也解释了我为什么我这么说。 就jdk源码层面来说 LinkedList本身维护了Node<E>类型的 first和last 头尾节点以实现双向链表的存储结构。 Vector 维护了一个 Object[]数组,并实现了对数组的各种操作,Stack只是根据栈的特性,提供了push\pop\peek\emty等方法,并调用父类(Vector)的方法来操作数组。 所以在这个层面上来说,确实将我的说法中"而Vector底层是AbstractList,是一个数组"改为"而Vector底层是Object[],是一个数组"更加稳妥。

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值